Loop Sets

Looping through sets in Python allows you to read and process unique elements efficiently. Because sets are unordered and unindexed, looping is the primary way to work with their data.
This topic explains all practical ways to loop through sets, with examples and best practices.

Loop Through a Set Using for

The most common and correct way to loop through a set.
python
fruits = {"apple", "banana", "cherry"}

for item in fruits:
    print(item)
Order is not guaranteed.

Loop Through a Set Using while (Indirect)

Sets do not support indexing, so while loops require conversion.
python
numbers = {1, 2, 3}
numbers_list = list(numbers)

i = 0
while i < len(numbers_list):
    print(numbers_list[i])
    i += 1

Loop and Apply Conditions

python
numbers = {10, 15, 20, 25}

for num in numbers:
    if num > 15:
        print(num)

Loop and Modify a Set (Safe Way)

You cannot modify a set while iterating over it directly.
Safe approach:
python
numbers = {1, 2, 3, 4, 5}

for num in list(numbers):
    if num % 2 == 0:
        numbers.remove(num)

print(numbers)

Loop Using Set Comprehension

Set comprehensions are clean and efficient.
python
numbers = {1, 2, 3, 4, 5}
even_numbers = {x for x in numbers if x % 2 == 0}
print(even_numbers)

Loop Through Nested Sets

python
nested = {frozenset({1, 2}), frozenset({3, 4})}

for s in nested:
    for item in s:
        print(item)

Loop Through Multiple Sets Using zip()

python
a = {1, 2, 3}
b = {4, 5, 6}

for x, y in zip(a, b):
    print(x, y)
Order pairing depends on internal ordering.

Loop Through a Frozen Set

python
fs = frozenset([10, 20, 30])

for item in fs:
    print(item)

Loop with break

python
numbers = {1, 2, 3, 4}

for n in numbers:
    if n == 3:
        break
    print(n)

Loop with continue

python
numbers = {1, 2, 3, 4}

for n in numbers:
    if n == 2:
        continue
    print(n)

Common Mistakes

Expecting Order

python
s = {1, 2, 3}
print(s)
Order is not fixed.

Modifying Set During Iteration

python
# for x in s:
#     s.remove(x)   # RuntimeError

Best Practices

  • Use for loop directly
  • Do not rely on element order
  • Convert to list if indexing is needed
  • Use set comprehension for filtering
  • Avoid modifying set during iteration

Summary

  • Sets are unordered collections
  • Looping is the primary access method
  • for loop is best
  • Set comprehension is powerful
  • Frozen sets are looped the same way
  • Order should never be assumed