Guide Python Beginner

12.10 Traversing Sets

Visiting every element of a set with a for loop and with enumerate() -- and why the indices enumerate() produces are meaningless as positions, useful only for counting as you go.

2 min read

for Loop

>>> for x in {1, 2, 3}:
...     print(x, end=" ")
1 2 3

enumerate()

Works on a set like any iterable, but the indices it produces are meaningless as “positions” (see 12.6 Set Indexing and Ordering) — useful only for counting as you go, not for later lookup.

>>> for i, v in enumerate({10, 20, 30}):
...     print(i, v)
0 10
1 20
2 30

Iteration Best Practices

Never assume a set’s iteration order matches insertion order or any other meaningful sequence — if order matters for the output, convert to a sorted list first with sorted(my_set).

Quick Interview Answer

“Traversing a set looks identical to traversing a list — a plain for loop is the default, and enumerate() works exactly the same mechanically. The catch is entirely about meaning, not syntax: the index enumerate() produces for a set element is not a position it can be looked up by later, and isn’t tied to insertion order either — it’s only useful as a running counter. Whenever the traversal’s output actually needs a stable, meaningful order, convert to a sorted list first rather than relying on however the set happens to iterate.”

Common Mistakes

  • Using enumerate() over a set and later trying to access my_set[i] with that index — sets aren’t subscriptable at all.
  • Assuming two loops over the “same” set in one run will visit elements in the same order as each other — usually true within a single unmodified set, but not something to build logic around.
  • Printing or logging a set directly for output that other systems will parse, without sorting first — the unordered rendering can differ across runs or Python versions.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form