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
my_set[0] to get the first element.for: use for element in my_set: to visit every item.enumerate(): gives you a running index while looping, but that index is not tied to any real position inside the set.if with the loop to filter or process specific items.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.
Loop through all elements in a set using a for loop.
# Define a set of fruits
fruits = {"apple", "banana", "cherry"}
# Loop through each fruit in the set
for fruit in fruits:
print(fruit)
Use enumerate() when you want a running index while looping a set. Remember: the index is just the loop count, because sets are unordered.
# 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}")
Combine loops with if conditions to process only certain elements, such as even numbers.
# 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
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:
For the even numbers example, only numbers divisible by 2 will be printed:
2 4 6
for loops to iterate through all set items.enumerate() only when you need a counter; don’t treat it like a real index into the set.enumerate() to print index and item for a set of fruits.type().10).