Loop Sets
Learn how to loop through Python sets using for loops, while loops, enumerate, break, continue, and set comprehensions with clear examples.
Python sets are unordered collections of unique elements. Because they are unordered, you cannot access items by index — but you can still iterate over every element with a for loop, use while loops to consume a set, and apply set operations inside loops to solve common data problems.
This page covers how to loop through sets in Python, including deterministic iteration with sorted(), enumerate(), filtering with break and continue, set comprehensions, and practical use cases.
Creating a Set
Before looping, you need a set. You can create one with curly braces {} or with the built-in set() function. See Python Sets for a full introduction.
Create a set in Python
# Using curly braces
fruits = {'apple', 'banana', 'cherry'}
# Using set() — useful when converting another sequence
numbers = set([1, 2, 2, 3, 4, 4, 5])
print(numbers) # {1, 2, 3, 4, 5} — duplicates are removedNotice that set() on a list automatically removes duplicates. The output order is not guaranteed.
Looping Through a Set with a For Loop
The most common way to iterate over a set is a for loop. Python visits every element once, but in an arbitrary order.
Iterate over a set in Python
Running this might print:
banana
cherry
appleThe order can differ every time the program runs. If you need a predictable order, wrap the set in sorted().
Iterating in Sorted Order
sorted() returns a regular list containing the set's elements in ascending order. The original set is unchanged.
Loop through a set in sorted order
fruits = {'apple', 'banana', 'cherry'}
for fruit in sorted(fruits):
print(fruit)Output:
apple
banana
cherryUse sorted(my_set, reverse=True) to iterate in descending order.
Using enumerate() with a Set
enumerate() pairs each element with a counter. Combined with sorted(), this gives you a stable index alongside each item.
Enumerate a set in Python
fruits = {'apple', 'banana', 'cherry'}
for index, fruit in enumerate(sorted(fruits)):
print(index, fruit)Output:
0 apple
1 banana
2 cherryThis is useful when you need to number items in a report or label them in a data pipeline.
Looping with break and continue
You can use break to stop the loop early and continue to skip specific elements.
Using continue to Skip Elements
Skip elements while looping a set
scores = {55, 72, 88, 64}
for score in sorted(scores):
if score < 60:
continue # skip failing scores
print(score)Output:
64
72
88Using break to Stop Early
Stop a loop early using break
scores = {55, 72, 88, 91, 64}
for score in sorted(scores):
if score >= 90:
print(f'First score at 90 or above: {score}')
breakOutput:
First score at 90 or above: 91Looping Through a Set with a While Loop
A while loop combined with pop() lets you process and consume a set element by element. Use this pattern when you want to drain the set as you go (for example, a work queue).
Use a while loop to consume a set
tasks = {'send email', 'write report', 'update database'}
while tasks:
task = tasks.pop() # removes and returns an arbitrary element
print(f'Processing: {task}')
print('All tasks done.')Output (order will vary):
Processing: update database
Processing: write report
Processing: send email
All tasks done.After the loop, tasks is empty. If you need the original set intact, work on a copy: tasks.copy().
Membership Testing Inside a Loop
One of the greatest strengths of sets is O(1) membership testing. Checking item in my_set is much faster than checking item in my_list for large collections, because sets use a hash table internally.
Filter a list using a set for fast lookups
allowed_roles = {'admin', 'editor', 'viewer'}
users = ['admin', 'guest', 'editor', 'unknown']
for user in users:
if user in allowed_roles:
print(f'{user}: access granted')
else:
print(f'{user}: access denied')Output:
admin: access granted
guest: access denied
editor: access granted
unknown: access deniedThis pattern is common for permission checks, blocklists, and data filtering.
Removing Duplicates from a List
Converting a list to a set inside a loop is a quick way to ensure you process each unique value only once.
Remove duplicates from a list using a set
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_values = set(my_list) # duplicates removed
for value in sorted(unique_values):
print(value)Output:
1
2
3
4
5Looping Over Set Operations
You can loop directly over the result of a set operation — union, intersection, difference — without creating an intermediate variable.
Loop over set operations in Python
Output:
Intersection:
3
4
Difference (set1 - set2):
1
2
Symmetric difference:
1
2
5
6See Join Sets for more on combining sets and Set Methods for the full list of operations.
Set Comprehensions
A set comprehension builds a new set from an expression in a single line. The syntax mirrors list comprehensions but uses curly braces.
Build a set with a set comprehension
# Squares of numbers 1 through 5
squares = {x**2 for x in range(1, 6)}
print(sorted(squares))Output:
[1, 4, 9, 16, 25]You can add a condition to filter elements:
Set comprehension with a filter
numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
evens = {n for n in numbers if n % 2 == 0}
print(sorted(evens))Output:
[2, 4, 6, 8, 10]Set comprehensions are more concise than a for loop that calls .add() in the body, and they communicate intent clearly. For list equivalents, see List Comprehension.
Key Takeaways
- Sets are unordered — do not rely on iteration order. Use
sorted()when a stable order matters. - Sets contain unique elements — iteration automatically skips duplicates.
inmembership checks on sets are O(1) — much faster than on lists for large data.pop()removes an arbitrary element and is useful for consuming a set in awhileloop.- Set comprehensions
{expr for item in iterable}are the idiomatic way to build a filtered or transformed set in one line.
Related Topics
- Python Sets — creating, adding, and removing elements
- Add Set Items —
add()andupdate()methods - Remove Set Items —
remove(),discard(), andpop() - Join Sets — union, intersection, difference, and more
- Set Methods — full reference for all set methods
- Python For Loops — the
forloop in depth - Loop Lists — iterating over lists
- Loop Tuples — iterating over tuples
- Loop Dictionaries — iterating over dictionaries