How to Iterate Over Set in Python: Simple Guide
To iterate over a
set in Python, use a for loop to access each element one by one. Since sets are unordered collections, the order of elements during iteration is not guaranteed.Syntax
Use a for loop to go through each element in the set. The syntax is simple:
for element in set_name:— loops over each itemelement— variable holding the current item
python
for element in set_name: # do something with element
Example
This example shows how to print each item in a set. Notice the order may vary because sets do not keep order.
python
my_set = {10, 20, 30, 40}
for item in my_set:
print(item)Output
40
10
20
30
Common Pitfalls
One common mistake is expecting the set to keep the order of items like a list. Sets are unordered, so the order of iteration can change each time.
Another mistake is trying to access elements by index, which is not possible with sets.
python
my_set = {1, 2, 3}
# Wrong: trying to access by index
# print(my_set[0]) # This will cause an error
# Right way: iterate with for loop
for num in my_set:
print(num)Output
1
2
3
Quick Reference
| Action | Syntax | Notes |
|---|---|---|
| Iterate over set | for item in my_set: | Access each element, order not guaranteed |
| Check membership | if item in my_set: | Fast lookup in sets |
| Add element | my_set.add(element) | Adds element if not present |
| Remove element | my_set.remove(element) | Removes element, error if missing |
| Discard element | my_set.discard(element) | Removes element if present, no error |
Key Takeaways
Use a for loop to iterate over each element in a set.
Sets are unordered, so do not expect elements in a fixed order.
You cannot access set elements by index like a list.
Iteration over sets is simple and efficient for unique items.
Remember sets support fast membership tests during iteration.