Loop Sets
Looping Through Sets
You can iterate through a set using a for loop. Since sets are unordered collections, the order of iteration is not guaranteed and may vary between runs.
# Basic looping through a set
fruits = {"apple", "banana", "cherry"}
print("Fruits in set:")
for fruit in fruits:
print(f"- {fruit}")
Fruits in set: - apple - banana - cherry
Looping with enumerate
If you need an index while looping, use enumerate(). The index is assigned in the order of iteration, but remember that set order is not predictable.
# Looping with index using enumerate
colors = {"red", "green", "blue"}
for index, color in enumerate(colors):
print(f"Color {index}: {color}")
Color 0: red Color 1: green Color 2: blue
Set Comprehension
Set comprehensions allow building sets concisely, similar to list comprehensions, and support expressions and conditions.
# Set comprehension example
numbers = {1, 2, 3, 4, 5}
# Create a new set with squared values
squared = {x**2 for x in numbers}
print(squared)
# Create a set with only even numbers
even_numbers = {x for x in numbers if x % 2 == 0}
print(even_numbers)
{1, 4, 9, 16, 25} {2, 4}
While Loop with Sets
You can also use a while loop with sets by repeatedly removing elements. This is less common but can be useful in certain scenarios. Use a copy if you want to preserve the original set.
# Using while loop with sets
numbers = {1, 2, 3, 4, 5}
temp_set = numbers.copy()
while temp_set:
item = temp_set.pop()
print(f"Removed: {item}")
print(f"Original set unchanged: {numbers}")
Removed: 1 Removed: 2 Removed: 3 Removed: 4 Removed: 5 Original set unchanged: {1, 2, 3, 4, 5}
Nested Loops with Sets
Nested loops allow comparing elements across multiple sets. While you can use built-in methods like intersection() for efficiency, nested loops can be used for custom comparisons.
# Comparing elements between two sets
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print("Common elements:")
for item1 in set1:
for item2 in set2:
if item1 == item2:
print(f"- {item1}")
Common elements: - 3 - 4