Python Tutorial
Python Loop Sets
You can loop through set items with a for loop.
for Loop
The order is not guaranteed.
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)📘 Real-World Deep Dive
Looping over a set is how you turn "which things are unique here?" into an answer. Because a set can't hold duplicates, iterating one is the natural finish to any dedup, tag-collection, or "seen already?" task.
Real-Life Scenario
A web server log lists one IP per request. We want the distinct visitors and a stable, human-readable report — which forces us to confront that sets have no order.
Real-Life Example
hits = ["8.8.8.8", "1.1.1.1", "8.8.8.8", "9.9.9.9", "1.1.1.1"]
unique = set(hits)
print(f"{len(unique)} unique visitors of {len(hits)} requests")
# A set has no order — sort it before you show it to a human.
for ip in sorted(unique):
print(ip)Never rely on the order a set loops in — call sorted() when the output is shown to a person or compared in a test.
Expected Output
3 unique visitors of 5 requests
1.1.1.1
8.8.8.8
9.9.9.9Common mistakes
- Set iteration order is not insertion order and can change between runs — a test that hard-codes the order will flake. Wrap it in
sorted(). - Mutating a set while looping over it (
for x in s: s.add(...)) raisesRuntimeError: Set changed size during iteration. Loop over a copy or build a new set. - Only hashable items go in a set — a set of lists throws
TypeError; use tuples instead.
🚀 Performance & Best Practices
- Membership testing (
x in s) is O(1) on a set vs. O(n) on a list — turning a list into a set before a lot of lookups is a common, big win. set(hits)dedups in one pass; a manual loop withif x not in resulton a list is O(n²).- If you also need "first seen" order,
dict.fromkeys(hits)dedups and preserves order.
🧪 Try It Yourself
- Report the visitor who appears most often (hint:
collections.Counter) alongside the unique count. - Given two days of logs, print the IPs that appear on both days using the
&set operator. - Rewrite the dedup with
dict.fromkeysand explain when you'd prefer it over a set.