B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Loop Through Sets in Python | LiveCodeProgramming
LiveCodeProgramming

Loop Through a Set in Python

You can loop through a Python set using several ways. Let's explore them with examples.

Python set में आप कई तरीकों से loop चला सकते हैं। नीचे सभी तरीके दिए गए हैं।

1. Using for loop
colors = {"red", "green", "blue"}
for color in colors:
    print(color)
Output:
red
green
blue
2. Using enumerate()
colors = {"red", "green", "blue"}
for index, color in enumerate(colors):
    print(index, color)
Output:
0 red
1 green
2 blue
3. Using sorted() with loop
colors = {"red", "green", "blue"}
for color in sorted(colors):
    print(color)
Output:
blue
green
red
4. Using while with iterator
colors = {"red", "green", "blue"}
it = iter(colors)
while True:
    try:
        print(next(it))
    except StopIteration:
        break
Output:
red
green
blue
5. Using Set Comprehension
colors = {"red", "green", "blue"}
upper_colors = {color.upper() for color in colors}
print(upper_colors)
Output:
{'GREEN', 'RED', 'BLUE'}