Ways to Loop through Set in Python


Loop through Set

Because the set is an unordered collection, indexes cannot be used to access the elements of the set. To loop through sets, we need to take advantage of the loop statements. In this tutorial, we will discuss the various ways by which we can iterate over the elements of the set.

Loop through Set

Using the for Loop

We can iterate over all the items in the set using the for loop. This is one of the easiest ways to iterate over the elements of the set. In the below example, we are using a for loop to iterate over the birds set.

In [1]:
birds = ("Parrot", "Crow", "Eagle")
for bird in birds:
    print(bird)
Parrot
Crow
Eagle

Using the enumerate() method

We can use the enumerate method to iterate over the elements of the set. The enumerate method will return us the counter along with the original elements of the set. This counter will start from 0 and go until the number of elements minus on1. In the below example, the counter starts at zero and goes until 5-1, i.e. 4.

In [1]:
birds = ("Parrot", "Crow", "Eagle")
for n, bird in enumerate(birds):
    print(n,"-",bird)
0 - Parrot
1 - Crow
2 - Eagle

By Converting set to list

We can type cast the set to the list, i.e. use the list constructor to convert the set to the list. Now we have the list, we can iterate over the element of the list using any technique like for loop, for loop with range, etc.

In [1]:
birds_set = ("Parrot", "Crow", "Eagle")

birds_list = list(birds_set)

for n in range(len(birds_list)):
    print(n, "-", birds_list[n])
0 - Parrot
1 - Crow
2 - Eagle

Using comprehension and unpacking

List Comprehension can be used to iterate over the elements of the set. Here, the asterisk can be used to unpack the elements of the list.

We can use the print statement in the comprehension itself to print the elements of the set there. As shown in the example number three below.

In [1]:
birds_set = ("Parrot", "Crow", "Eagle")

birds = list(bird for bird in birds_set)

print(*birds)
Parrot Crow Eagle

Converting to a list using the square brackets [].

In [2]:
birds_set = ("Parrot", "Crow", "Eagle")

birds = [bird for bird in birds_set]

print(*birds)
Parrot Crow Eagle

Directly printing elements of the set.

In [3]:
birds_set = ("Parrot", "Crow", "Eagle")

birds = [print(bird) for bird in birds_set]
Parrot
Crow
Eagle

Using the iter() funciton

In Python, the iter() function is a built-in function that is used to obtain an iterator from an object. The iter() function takes an iterable object (like list, tuple, set, etc.) as an argument and returns an iterator for that object.

The iter() function is used in combination with the next() function. The next() function is used to retrieve the next element from an iterator. In the below example, we are using the iter() function to create the iterator of the numbers, and next is used to fetch the next element.

When the next() reaches the end of the iterator, it raises a StopIteration error, to catch that error try-except block is used.

In [1]:
birds_set = ("Parrot", "Crow", "Eagle")

# Creating an iterator object
iterator = iter(birds_set)

# printing elements of set
# The next function is retrieving elements
try:
    while True:
        item = next(iterator)
        print(item)
except StopIteration:
    pass
Parrot
Crow
Eagle

Using the zip() function

The zip() function in Python is a built-in function that allows us to combine elements from multiple iterables (such as lists, tuples, sets, etc.) into tuples. It pairs up the elements of the input iterables element-wise, creating an iterator of tuples. The i-th tuple contains the i-th elements from each of the input iterables.

In [1]:
numbers = (24, 25, 26)
characters = ('x', 'y', 'z')
 
#  zip() to iterate over both the sets
for i, j in zip(numbers, characters):
    print(i, "-", j)
24 - x
25 - y
26 - z

References:

  1. Iterate over a set in Python