Member-only story
Hi everyone, welcome back. For loops are used in Python to iterate over a sequence such as a list, a set, or even the characters in a string. There are many uses for this type of capability and we will go over how for loops works. Let’s get into it.
Iterating Through a List
In this first example, we will create a list and iterate through it. We will also print out each item as we are looping through:
list = ["strings", "numbers", "booleans"]
for x in list:
print(x)Output:
strings
numbers
booleans
In the example above, we can see that we have created a list containing three items. Then we have our for loop, in which we are setting each item to a new variable, x, and printing it.
Iterating Through a String
Now, let’s see an example of us iterating through the characters if a string. Just like in the first example, we will be printing out each item as we are looping through it:
for x in "string":
print(x)Output:
s
t
r
i
n
g
In this example, we can see that each iteration goes through a single character at a time.