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
appleSets 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
PythonUse
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: 25Apply 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 oldUnpack 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
| Task | Syntax | Note |
|---|---|---|
| Basic loop | for x in myset: | No order |
| Indexed loop | for i, x in enumerate(myset): | Index not based on order |
| Sorted loop | for x in sorted(myset): | Alphabetical/numerical |
| Comprehension | {x for x in myset if condition} | Creates a new set |