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 { }
.
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.
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.
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
.
In the below code, we print all the items in the set one by one.
# creating a setcountries = {"USA", "CHINA", "TURKEY"}# using a for loopfor element in countries:print(element)
countries
.for
loop to create an expression. This makes x
become each element 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.
# creating a setcountries = {"USA", "CHINA", "TURKEY"}# converting the set to a listmylist = list(countries)# using the index value and calling the len() functionfor index in range(len(mylist)):print(mylist[index])
countries
.list()
function to convert the set variable to a list variable, mylist
. This allows us to iterate over items.len()
function. Next, we iterate over the items and print them.