← Back to Chapters

Python Looping Through Sets

? Python Looping Through Sets

⚡ Quick Overview

In Python, a set is an unordered collection of unique elements. Because sets do not keep items in a fixed order, you cannot access elements using indexes like you do with lists or tuples. Instead, you typically use a for loop to iterate over all items in the set.

You can also combine loops with functions like enumerate() and use conditional statements inside the loop to process only the elements you care about.

✨ Key idea: iterate, don’t index

? Key Concepts

  • Unordered collection: sets do not preserve insertion order (in practice, the order is not guaranteed).
  • No indexing: you cannot do my_set[0] to get the first element.
  • Looping with for: use for element in my_set: to visit every item.
  • Using enumerate(): gives you a running index while looping, but that index is not tied to any real position inside the set.
  • Conditionals in loops: combine if with the loop to filter or process specific items.
  • Don’t rely on order: the sequence in which items appear during iteration can vary between runs.

? Syntax and Behavior

Basic loop syntax with a set:

for item in my_set: → executes the loop body once for each element in the set.

With enumerate():

for index, item in enumerate(my_set): → gives you a counter index along with each item. The index is just the loop counter, not a true “position” in the set.

? Code Examples

? Basic Loop Through a Set

Loop through all elements in a set using a for loop.

? View Code Example
# Define a set of fruits
fruits = {"apple", "banana", "cherry"}

# Loop through each fruit in the set
for fruit in fruits:
    print(fruit)

? Using enumerate() with a Set

Use enumerate() when you want a running index while looping a set. Remember: the index is just the loop count, because sets are unordered.

? View Code Example
# Define a set of fruits
fruits = {"apple", "banana", "cherry"}

# Use enumerate() to get a counter and each fruit
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")

? Looping with Conditionals

Combine loops with if conditions to process only certain elements, such as even numbers.

? View Code Example
# Define a set of numbers
numbers = {1, 2, 3, 4, 5, 6}

# Loop through the set and print even numbers
for num in numbers:
    if num % 2 == 0:
        print(num)  # prints only even numbers

? Live Output & Explanation

? What kind of output should you expect?

For the fruit example, you will see each fruit printed on a new line. However, the exact order is not guaranteed because sets are unordered:

apple
banana
cherry

Or it might appear as:

cherry
apple
banana

Both are correct. The important part is that:

  • Each unique element appears exactly once.
  • You should not rely on any specific order when looping through a set.

For the even numbers example, only numbers divisible by 2 will be printed:

2
4
6

✅ Tips

  • Use simple for loops to iterate through all set items.
  • Use enumerate() only when you need a counter; don’t treat it like a real index into the set.
  • Use conditional statements inside the loop to filter items (e.g., only even numbers, only strings starting with a letter).
  • Avoid modifying the set (adding/removing elements) while iterating over it to prevent unexpected behavior.
  • Never assume the iteration order is predictable—if you need order, consider using a list or a sorted view of the set.

? Use Cases

  • Checking membership and looping through unique items (e.g., unique user IDs, tags, categories).
  • Filtering data where duplicates are not important but fast membership checks are.
  • Performing set operations (union, intersection, difference) and then iterating through the result.

? Try It Yourself

  • Loop through a set of numbers and print only odd numbers.
  • Use enumerate() to print index and item for a set of fruits.
  • Create a set of mixed data types and loop through it, printing each item and its type using type().
  • Loop through a set of numbers and print only the items greater than a certain value (for example, greater than 10).