You can loop through a Python set using several ways. Let's explore them with examples.
Python set में आप कई तरीकों से loop चला सकते हैं। नीचे सभी तरीके दिए गए हैं।
for
loopcolors = {"red", "green", "blue"}
for color in colors:
print(color)
Output:
red green blue
enumerate()
colors = {"red", "green", "blue"}
for index, color in enumerate(colors):
print(index, color)
Output:
0 red 1 green 2 blue
sorted()
with loopcolors = {"red", "green", "blue"}
for color in sorted(colors):
print(color)
Output:
blue green red
while
with iteratorcolors = {"red", "green", "blue"}
it = iter(colors)
while True:
try:
print(next(it))
except StopIteration:
break
Output:
red green blue
colors = {"red", "green", "blue"}
upper_colors = {color.upper() for color in colors}
print(upper_colors)
Output:
{'GREEN', 'RED', 'BLUE'}