Loop Through Sets

Sets in Python are unordered collections of unique elements. Although the items in a set are unordered, you can still loop through them using a for loop to perform operations on each element.

Using a for Loop

The for loop is commonly used to iterate through all items in a set. Since sets are unordered, the elements may be accessed in a different order each time you loop through them.

Python
fruits = {"apple", "banana", "cherry"}

for fruit in fruits:
    print(fruit)

# Output (order may vary):
# apple
# banana
# cherry

This example demonstrates how to loop through a set and print each item. Keep in mind that the order of items in a set is not preserved, so the output order may vary.

Checking for Membership During Looping

While looping through a set, you might want to check if a particular item meets a condition, such as belonging to a specific category or having a certain property.

Python
fruits = {"apple", "banana", "cherry"}

# Check for a specific item
for fruit in fruits:
    if fruit == "banana":
        print("Banana is in the set!")

# Output:
# Banana is in the set!

This example checks for the presence of "banana" in the set during the loop and performs an action if the condition is met.

Using a Set to Remove Duplicates

One of the primary uses of a set is to remove duplicate items from a list or another iterable. You can loop through the resulting set to access unique items.

Python
numbers = [1, 2, 2, 3, 4, 4, 5]

# Convert the list to a set to remove duplicates
unique_numbers = set(numbers)

# Loop through the set of unique numbers
for number in unique_numbers:
    print(number)

# Output (order may vary):
# 1
# 2
# 3
# 4
# 5

By converting a list to a set, duplicates are automatically removed. Looping through the set then allows you to access each unique item.

Practical Example: Filtering Unique Elements

Consider a scenario where you have a list of words, and you want to print only the unique words. Using a set, you can easily achieve this:

Python
words = ["apple", "banana", "apple", "cherry", "banana", "date"]

# Convert the list to a set to get unique words
unique_words = set(words)

# Loop through and print each unique word
for word in unique_words:
    print(word)

# Output (order may vary):
# apple
# banana
# cherry
# date

This example highlights how to filter and display unique items from a collection, demonstrating the practical use of sets in Python.