Related Tags

loop
python
set
for-loop
communitycreator

# How to loop through a set using a for loop in Python

Onyejiaku Theophilus Chidalu

### Overview

In Python, a set is used to store unordered and unchangeable multiple items in a single variable. In a code, sets are defined by values between braces { }.

### Defining a set

countries = {"USA", "CHINA", "TURKEY"}


In the above example, we see that countries is a set variable whereas "USA", "CHINA", and "TURKEY" are the elements of the set.

### Looping through a set in Python

To loop through a set in Python means to repeat something multiple times in the elements of the set. The loop runs until a particular condition is satisfied.

We can loop through a set in Python using a for loop.

### Syntax

for (expression):
statement(s)


The expression given in the code above is conventionaly a condition. The statement will execute when the condition given is True.

### Example 1

In the below code, we print all the items in the set one by one.

# creating a set
countries = {"USA", "CHINA", "TURKEY"}

# using a for loop
for element in countries:
print(element)
Looping through a set using a for loop

### Explanation

• Line 2: We create a set, countries.
• Line 5: We use a for loop to create an expression. This makes x become each element of the set.
• Line 6: We print all the elements of the set.

We use an index variable and call the len() function to iterate over a set. In order to do this, we’ll have to first convert the set to a list object in order to iterate over the items.

### Example 2

# creating a set
countries = {"USA", "CHINA", "TURKEY"}

# converting the set to a list
mylist = list(countries)

# using the index value and calling the len() function
for index in range(len(mylist)):
print(mylist[index])


Iterating over a set using the index and len() function

### Explanation

• Line 2: We create a set, countries.
• Line 5: We use the list() function to convert the set variable to a list variable, mylist. This allows us to iterate over items.
• Line 8 and 9: We use the index and call the len() function. Next, we iterate over the items and print them.

RELATED TAGS

loop
python
set
for-loop
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time