Python Iterate Set Tutorial

In this section, we will learn how to iterate through the elements of a Set object in Python.

Python Iterate Set: How to Iterate Through a Set in Python?

In order to loop through the elements of a Set object, we can use the `for in` loop.

All we need to do is to set the iterable object of the `for in` loop to the target Set object and after that, we can access the entire elements in the body of the `for` loop.

Example: Python Loop through Set via for Loop

set1 = {"Ellen","Jack", "Omid",False,"Elon", 20.3, "James","Richard","Jeremy", "Ian","Elon", "Kimberly"}

num = 0
for element in set1:
    print(f"{num}: {element}")
    num +=1

Output:

0: False

1: Jack

2: Elon

3: Kimberly

4: Omid

5: James

6: Ellen

7: Ian

8: 20.3

9: Jeremy

10: Richard

Leave a Reply