Python – Loop Sets

In Python, you can loop through a set using a for loop. Since sets are unordered collections of unique elements, the order of elements may vary each time you iterate over the set.

Looping through a Set

1. Basic Loop

You can loop through each item in a set directly using a for loop.

Example:

# Given set
my_set = {10, 20, 30, 40, 50}

# Loop through the set
for item in my_set:
    print(item)

Output (the order may vary since sets are unordered):

10
20
30
40
50

Each time you run the program, the order of elements might change because sets are unordered.


2. Looping with enumerate()

If you want to keep track of the index of the elements while looping through the set, you can use the enumerate() function. Although sets do not have indices, enumerate() can provide an index-like number as you loop through the elements.

Example:

# Given set
my_set = {10, 20, 30, 40, 50}

# Loop through the set with enumerate
for index, item in enumerate(my_set):
    print(f"Index {index}: {item}")

Output (the index numbers will be sequential, but the order of elements will still vary):

Index 0: 10
Index 1: 20
Index 2: 30
Index 3: 40
Index 4: 50

3. Looping Through a Set Using iter()

You can also loop through a set using the iter() function, which returns an iterator for the set. You can then use next() to get each element from the set.

Example:

# Given set
my_set = {10, 20, 30, 40, 50}

# Create an iterator for the set
set_iter = iter(my_set)

# Loop through the set using next()
print(next(set_iter))  # Print first element
print(next(set_iter))  # Print second element

Output (order of items will vary):

10
20

4. Looping Through Set Using Set Comprehension

You can also use set comprehension to create a new set or process each element in the original set.

Example (creating a new set with squared values):

# Given set
my_set = {1, 2, 3, 4, 5}

# Create a new set with squares of each element
squared_set = {x**2 for x in my_set}

print("Squared Set:", squared_set)

Output:

Squared Set: {1, 4, 9, 16, 25}

Summary:

  • For Loop: Use a for loop to iterate through all elements in the set.
  • enumerate(): Use enumerate() if you need an index while looping.
  • iter() and next(): Use iter() and next() if you want to manually iterate over the set.
  • Set Comprehension: Use set comprehension to process and create new sets.
Leave a Reply 0

Your email address will not be published. Required fields are marked *