Open In App

Iterate over a set in Python

Last Updated : 22 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The goal is to iterate over a set in Python. Since sets are unordered, the order of elements may vary each time you iterate. You can use a for loop to access and process each element, but the sequence may change with each execution. Let’s explore different ways to iterate over a set.

Using for loop

When you use a for loop, Python automatically calls the __iter__() method behind the scenes, which handles the iteration for you. This makes it simple and efficient to go through all the elements, without the need for things like indices.

Python
a = set("geEks")

for i in a:
    print(i)

Output
s
g
e
k
E

Explanation: set() function creates an unordered collection of unique characters from the string, and the for loop prints each character once in random order.

Using set.__iter__()

set.__iter__() lets you directly access the internal iterator of a set. It does the same thing a for loop does behind the scenes but in a more manual way. While rarely used in everyday code, it’s helpful when you want to understand or control how iteration works under the hood.

Python
a = set("geEks")

for i in a.__iter__():
    print(i)

Output
E
s
g
k
e

Explanation: __iter__() method returns an iterator for the set, and the for loop uses it to print each unique character. As sets are unordered, the output order may vary each time.

Using iter()

iter() function returns an iterator for a given iterable, like a set. It’s essentially a cleaner and more readable way to call __iter__() directly.

Python
a = set("geEks")

for i in iter(a):
    print(i)

Output
g
e
s
k
E

Explanation: iter(a) function returns an iterator for the set and the for loop prints each character in an unordered sequence, which may vary each time.

Using enumerate()

enumerate() is a built-in Python function that adds a counter (index) to an iterable. It returns each item as a tuple containing the index and the corresponding value.

Python
a = set("geEks")

for idx, i in enumerate(a):
    print(i)

Output
E
g
s
k
e

Explanation: enumerate(a) function adds an index to each element, but since sets are unordered, the index and output sequence may vary each time.


Next Article
Practice Tags :

Similar Reads