A for
loop in Python allows us to access each item of sequences (string, list, tuples, etc.) by iterating through them.
Sequences in Python
A sequence is a collection of items in an order. For example, a string is a sequence of characters.
# string as a sequence
text = 'Python'
# list as a sequence
even_numbers = [2, 4, 6, 8]
Here, we have created two sequences:
- text (string) - sequence of characters. To learn more, visit Python String.
- even_numbers (list) - sequence of numbers separated by commas and enclosed in square brackets. To learn more, visit Python List.
Python for Loop
Let's see the syntax to create the for
loop in Python.
for item in sequence:
# code
Here, the code inside the for
loop is executed for every item in the sequence.
Example: Python for Loop
# create a sequence
text = "Python"
# access each character
for item in text:
print(item)
Output
P y t h o n
In the above code, we are accessing the individual character of the string using a for
loop. Here's how the code works:
Iteration | Value of item | Inside Loop |
---|---|---|
First | P |
prints the value P |
Second | y |
prints the value y |
Third | t |
prints the value t |
Fourth | h |
prints the value h |
Fifth | o |
prints the value o |
Sixth | n |
prints the value n |
The loop continues until it reaches the last item in the sequence. Here, the string has 6 characters, so the loop runs 6 times.
Looping Through a List
We can also use the for
loop to iterate through a list. For example,
# create a list of numbers
numbers = [1, 2, 3, 4, 5]
# access each numbers
for num in numbers:
print(num)
Output
1 2 3 4 5
In the above example, we have created a numeric number and used a for
loop to access each number of the list. Here's the detailed working of the code.
Iteration | Value of num | Inside Loop |
---|---|---|
First | 1 | prints the value 1 |
Second | 2 | prints the value 2 |
Third | 3 | prints the value 3 |
Fourth | 4 | prints the value 4 |
Fifth | 5 | prints the value 5 |
We can also use the for
loop to iterate through the list of strings.
# create a list of strings
names = ['Steve', 'Maria', 'Ruby', 'Jackson']
# access each list value
for name in names:
print(name)
Output
Steve Maria Ruby Jackson
break Statement with for Loop
So far, our loop ends only when all the items of a sequence are accessed. However, we can also terminate the loop using the break
statement.
The break
statement inside the for
loop immediately ends the loop. For example,
# create a list of strings
names = ['Steve', 'Maria', 'Ruby', 'Jackson']
# access each list value
for name in names:
if (name == 'Maria'):
break
print(name)
# Output: Steve
In the above example, we have used the break
statement that is executed if the value of name is 'Maria'
.
When we run this code, we are only getting Steve
as output. Let's understand the working of this for loop.
Iteration | name | name == 'Maria'? |
---|---|---|
First | 'Steve' |
The condition is false, so break is not executed. |
Second | 'Maria' |
The condition is true, so break is executed, which terminates the loop. |
To learn more about the working of the break statement, visit Python break Statement.
continue Statement with for Loop
When we use the continue
statement with a for
loop, it skips the current iteration of the loop and starts the next iteration. Let's see an example.
# create a list of strings
names = ['Steve', 'Maria', 'Ruby', 'Jackson']
# access each list value
for name in names:
if (name == 'Maria'):
continue
print(name)
Output
Steve Ruby Jackson
In the above example, we have used the continue statement that is executed when the value of name is 'Maria'
.
If you look at the output, you can see the value 'Maria'
is not printed. Let's see how this for
loop is working in each iteration of the loop.
name | name == 'Maria'? | Inside Loop |
---|---|---|
'Steve' |
The condition is false, so continue is not executed. |
'Steve' is printed. |
'Maria' |
The condition is true, so continue is executed, which skips the loop's current iteration. |
'Maria' is not printed. |
'Ruby' |
The condition is false, so continue is not executed. |
'Ruby' is printed. |
'Jackson' |
The condition is false, so continue is not executed. |
'Jackson' is printed. |
To learn more about continue, visit Python continue statement.
for Loop with range()
So far we have used the for
loop to access each item of a sequence. However, we can also run the loop a certain number of times using the range()
function.
Let's see an example. Suppose we want to run our loop 5 times.
# for loop to run for 5 times
for count in range(1, 6):
print('Running for Loop')
Output
Running for Loop Running for Loop Running for Loop Running for Loop Running for Loop
Here, we have used the loop to print 'Running for Loop'
5 times using the range(1, 6)
function. In this case, the range()
function will create a sequence of numbers from 1 to 5 (the second value 6 is exclusive).
Then, the for
loop runs for each value of the sequence.
We can verify this by printing the value of count instead.
# for loop to run for 5 times
for count in range(1, 6):
print(count)
Output
1 2 3 4 5
To learn more about the range()
function, visit Python range().
Example: Multiplication Table
Let's create one more example. This time we will use the for
loop with range()
to create a multiplication table.
number = int(input('Enter a number: '))
for count in range(1, 11):
product = number * count
print(number, '*', count, '=', product)
Output
Enter a number: 7 7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49 7 * 8 = 56 7 * 9 = 63 7 * 10 = 70
The above code can create the multiplication table of any value that is provided as input.
Nested for Loop in Python
Python allows us to include one for
loop inside another, known as nested for loop. For example,
# outer for loop
for number in range(1, 3):
# inner for loop
for value in range(1, 6):
product = number * value
print(number, '*', value, '=', product)
Output
1 * 1 = 1 1 * 2 = 2 1 * 3 = 3 1 * 4 = 4 1 * 5 = 5 2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 2 * 4 = 8 2 * 5 = 10
In the above example, the outer loop executes 2 times (number = 1 and 2). In each iteration of the outer loop, the inner loop executes 5 times (value = 1, 2, 3, 4, and 5).
Hence, altogether the loop runs 10 times.
else with for Loop
The Python for
loop can have an optional else
block which is executed once the loop execution is completed. For example,
# outer for loop
for number in range(1, 3):
# inner for loop
for value in range(1, 6):
product = number * value
print(number, '*', value, '=', product)
else:
print('Multiplication Table for', number, 'is completed.')
Output
1 * 1 = 1 1 * 2 = 2 1 * 3 = 3 1 * 4 = 4 1 * 5 = 5 Multiplication Table for 1 is completed. 2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 2 * 4 = 8 2 * 5 = 10 Multiplication Table for 2 is completed.
In the above example, notice the inner for
loop.
for value in range(1, 6):
...
else:
....
Here, we have added an else
block with the for
loop. Once the inner for
loop is completed, the else
block is executed.
Hence, we get 'Multiplication Table for 1 is completed'
and 'Multiplication Table for 2 is completed'
in the output.
Recommended Reading: Python while loop