Python for loop

The for loop in Python is used to traverse over a sequence(list, tuples, dictionaries, etc). Traversal simply means accessing each item of a sequence one by one. The for loop in Python is similar to for each loop in other programming languages.


Syntax of the for Loop

for var in sequence:
    body of the loop

The var is the variable that holds the value of each item one by one in a given sequence. The sequence may be a list, string, dictionary, tuple, etc. The loop continues its execution until it accesses each item of the given sequence. Once all items are accessed the loop terminates. Refer the image below:

Python for loop

Example 1:

# A program to demonstrate for loop in Python

for i in range(5):
    print(i)

Output:

0
1
2
3
4

Note: The range() is an inbuilt function in Python. It returns a sequence of numbers. In the above example, the range(5) returns a sequence of numbers starting from 0 up to 4. Similarly, if you use range(10), it will return a sequence of numbers from 0 to 9. You can also provide a starting point, step size, and end to the range() function. Refer below example

Example 2:

# A program to demonstrate Python for loop with the range() function

# Providing a starting and endpoint in range method
print('Passing a starting and endpoint to the range function')
for i in range(5,10):
    print(i)
    
# Providing a starting point, step size and end point in the range() function
print('\nPassing a starting point, step size and end point')
for i in range(5,10,2):
    print(i)
 

Output:

Passing a starting and end point to the range function
5
6
7
8
9

Passing a starting point, step size and end point
5
7
9

Applying for Loop over a list, string and dictionary

Applying a for loop to a list, string or a dictionary traverse each item of it one by one.

At first, it holds the first item. After accessing the first item it moves to the second item, then third, and so on until all items are accessed. See the example below:

# A program to demonstrate for loop in Python

# Applying for loop over a list
my_list = [1, 2, 'Programmers', 'Portal']
print('For loop over a list.')
for item in my_list:
    print(item)

# Applying for loop over a string
str = 'abc'
print('\nFor loop over a string.')
for a in str:
    print(a)
    
# Applying for loop over a dictionary
my_dict = {
    'Name':'Programmers Portal',
    'Topic':'Python'
}
print('\nFor loop over a dictionary.')
for item in my_dict:
    print(item,': ',my_dict[item])
 

Output:

For loop over a list.
1
2
Programmers
Portal

For loop over a string.
a
b
c

For loop over a dictionary.
Name :  Programmers Portal
Topic :  Python

Using Indexes to Access Items

Indexes can be used to access items of an ordered sequence(lists, tuples, arrays, etc). Refer below example:

# A program to traverse items using index in Python

my_list = [1, 'Welcome', 'to', 'Programmers', 'Portal', 2]
for i in range(len(my_list)):
    print(my_list[i])

Output:

1
Welcome
to
Programmers
Portal
2

Note: len() is an inbuilt function in Python. It returns length of the sequence which is passed as a parameters.


A single line for loop

It is also possible to put body of the for loop and the for loop itself in the same line. Refer below example:

# A program to demonstrate an inline for loop

for i in range(5): print(i)

Output:

0
1
2
3
4

The for loop with the else Statement

In Python, it is also possible to use an else statement with the for loop. The code inside the else statement is executed when the for loop finishes its execution. Refer below example:

# A program to explain for loop with the else statement.

my_list = ['Welcome','to','Programmers', 'Portal']
for i in my_list:
    print(i)
else:
    print('Inside the else statement.')

Output:

Welcome
to
Programmers
Portal
Inside the else statement.

The break Statement

In the previous tutorial, we used the break statement with the while loop. Similarly, we can use a break statement with a for loop. The break statement is used when we want to stop the normal flow of the loop if a given condition occurs.

# A program to explain the break statement in Python

for i in range(5):
    if i == 3:   # Stop the loop if i is 3
        break
    print(i)

Output:

0
1
2

From the above example we can see that the for loop stops it’s execution once value of i becomes 3.


The continue Statement

The continue statement is used when we want to skip the execution of the loop for a given condition. But the loop should run normally for the rest of the conditions. For example, You want to print numbers from 1 to 10 except number 5.

# A program to explain the continue statement in Python

for num in range(1,11):
    if num == 5:  # If number is 5 skip it
        continue
    print(num)

Output:

1
2
3
4
6
7
8
9
10

As you can see in above output number 5 is missing. This is because at num == 5 the loop skips the execution.