Python Loop Through Sets | How to Loop Over Set Elements

Python Loop Through Sets

In Python, sets are unordered collections of unique items. You can loop through all the items in a set using a for loop. Since sets are unordered, the order of iteration is not guaranteed.

Python में sets अद्वितीय items का एक unordered संग्रह होते हैं। आप for loop की मदद से set के सभी items को loop कर सकते हैं। चूंकि sets unordered होते हैं, इसलिए iteration का order निश्चित नहीं होता।

Example 1: Basic for loop to iterate set elements
fruits = {'apple', 'banana', 'cherry'}
for fruit in fruits:
    print(fruit)

Use a for loop to access each element of the set one by one.

for loop से set के प्रत्येक element को access करें।

Output:

banana
apple
cherry
Example 2: Loop through a set and check condition
numbers = {1, 2, 3, 4, 5}
for num in numbers:
    if num % 2 == 0:
        print(f"{num} is even")
    else:
        print(f"{num} is odd")

Check each number in the set and print if it's even or odd.

Set के प्रत्येक नंबर के लिए जाँच करें कि वह even है या odd।

Output:

1 is odd
2 is even
3 is odd
4 is even
5 is odd
Example 3: Loop with enumerate to get index (not recommended for sets)
items = {'a', 'b', 'c'}
for i, item in enumerate(items):
    print(f"Index {i}: {item}")

You can use enumerate to get index, but since set is unordered, index order is not fixed.

enumerate से index प्राप्त कर सकते हैं, पर set unordered होने की वजह से index का order निश्चित नहीं होता।

Output:

Index 0: b
Index 1: a
Index 2: c
Example 4: Loop through a set and add items to a list
colors = {'red', 'green', 'blue'}
color_list = []
for color in colors:
    color_list.append(color)
print(color_list)

Loop through set and add each item to a list.

Set के items को loop करके एक list में डालें।

Output:

['green', 'red', 'blue']
Example 5: Nested loop with sets
set1 = {1, 2}
set2 = {'a', 'b'}
for num in set1:
    for char in set2:
        print(num, char)

Use nested loops to combine elements from two sets.

दो sets के elements को nested loops से combine करें।

Output:

1 a
1 b
2 a
2 b