Python – Iterate over Elements of Set

Python – Iterate over Elements of Set

To iterate over the elements of a Set in Python, we can use For loop statement.

Python For loop statement can be used to loop over the elements of given iterator object, which is a Set object in this case.

A simple code snippet to iterate over elements of a set x is

for element in x:
    #do something

Example

In the following program, we take a set x with fruit names, iterate over the elements of this set using For Loop, and print the element inside the For Loop.

Python Program

x = {"apple", "banana", "cherry"}
for element in x:
    print(element)
Run Code Copy

Output

cherry
apple
banana

Summary

In this tutorial of Python Examples, we learned how to check if given element is present in the set or not using Python-in keyword.

Code copied to clipboard successfully 👍