Python for Loop

In this tutorial, we'll learn how to use a for loop in Python with the help of examples.

Video: Python for Loop

In computer programming, loops are used to repeat a block of code.

For example, if we want to show a message 100 times, then we can use a loop. It's just a simple example; you can achieve much more with loops.

There are 2 types of loops in Python:


Python for Loop

In Python, the for loop is used to run a block of code for a certain number of times. It is used to iterate over any sequences such as list, tuple, string, etc.

The syntax of the for loop is:

for val in sequence:
    # statement(s)

Here, val accesses each item of sequence on each iteration. Loop continues until we reach the last item in the sequence.


Flowchart of Python for Loop

How for loop works in Python
Working of Python for loop

Example: Loop Over Python List

languages = ['Swift', 'Python', 'Go', 'JavaScript']

# access items of a list using for loop
for language in languages:
    print(language)

Output

Swift
Python
Go
JavaScript

In the above example, we have created a list called languages.

Initially, the value of language is set to the first element of the array,i.e. Swift, so the print statement inside the loop is executed.

language is updated with the next element of the array and the print statement is executed again. This way the loop runs until the last element of an array is accessed.


Python for Loop with Python range()

A range is a series of values between two numeric intervals.

We use Python's built-in function range() to define a range of values. For example,

values = range(4)

Here, 4 inside range() defines a range containing values 0, 1, 2, 3.

In Python, we can use for loop to iterate over a range. For example,

# use of range() to define a range of values
values = range(4)

# iterate from i = 0 to i = 3
for i in values:
    print(i)

Output

0
1
2
3

In the above example, we have used the for loop to iterate over a range from 0 to 3.

The value of i is set to 0 and it is updated to the next number of the range on each iteration. This process continues until 3 is reached.

Iteration Condition Action
1st True 0 is printed. i is increased to 1.
2nd True 1 is printed. i is increased to 2.
3rd True 2 is printed. i is increased to 3.
4th True 3 is printed. i is increased to 4.
5th False The loop is terminated

Note: To learn more about the use of for loop with range, visit Python range().


Python for loop with else

A for loop can have an optional else block as well. The else part is executed when the loop is finished. For example,

digits = [0, 1, 5]

for i in digits:
    print(i)
else:
    print("No items left.")

Output

0
1
5
No items left.

Here, the for loop prints all the items of the digits list. When the loop finishes, it executes the else block and prints No items left.

Note: The else block will not execute if the for loop is stopped by a break statement.

Did you find this article helpful?