Python Loop Sets

Python sets are iterable, allowing you to loop through each item using a for loop. Since sets are unordered, the items may appear in a different order every time.

1. Loop Through Set Using for Loop

fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
   print(fruit)

Output (order may vary):

banana  
cherry  
apple

Sets do not maintain order, so don’t rely on sequence.

2. Use enumerate() with Sets

fruits = {"apple", "banana", "cherry"}
for index, fruit in enumerate(fruits):
   print(f"{index}: {fruit}")

Output (index is assigned in arbitrary order):

0: banana  
1: cherry  
2: apple

enumerate() gives an index-like value even though the set has no guaranteed order.

3. Loop Through Sorted Set

languages = {"Python", "Java", "C++", "Go"}
for lang in sorted(languages):
   print(lang)

Output

C++  
Go  
Java  
Python

Use sorted(set) to process items in a predictable order.

4. Loop and Apply Condition

numbers = {5, 10, 15, 20, 25}
for num in numbers:
   if num > 10:
       print("Large number:", num)

Output:

Large number: 15  
Large number: 20  
Large number: 25

Apply logic to items during iteration.

5. Loop Through a Set of Tuples

users = {("Alice", 25), ("Bob", 30)}
for name, age in users:
   print(f"{name} is {age} years old")

Output:

Alice is 25 years old  
Bob is 30 years old

 Unpack multiple values in a loop when elements are tuples.

6. Loop to Build a New Set (Comprehension Style)

nums = {1, 2, 3, 4, 5}
squared = {x*x for x in nums}
print(squared)

Output:

{1, 4, 9, 16, 25}

Set comprehensions are concise ways to create filtered or transformed sets.

Summary Table

TaskSyntaxNote
Basic loopfor x in myset:No order
Indexed loopfor i, x in enumerate(myset):Index not based on order
Sorted loopfor x in sorted(myset):Alphabetical/numerical
Comprehension{x for x in myset if condition}Creates a new set