Skip to main content

Python for Loop

The for loops are used when you have a block of code which you want to repeat a fixed number of times.

Syntax

The for loop assigns each value contained in a given iterable to a variable and repeats the code in the body of the loop for each value taken by the variable.

note

The loop continues until the last element of the iterable is reached.

The syntax of the for loop is as follows

for <var> in <iterable>:
<statement>
<statement>
...

where:

  • <iterable> is a collection of objects, such as list, tuple, string, array, etc.
  • The loop variable <var> takes the value of the next element in <iterable> each time.
  • All <statements> are executed once for each element of the <iterable>.

For example:

for num in range(4):
print(num)

Output

0
1
2
3

for loop with else

A for loop can also have an optional else block. The else part is executed if the elements of the iterable used in the for loop run out.

note

The else statements are executed only if the for loop ends naturally.

The syntax is the same as a classic for loop, but with the addition of the else branch:

for <var> in <iterable>:
<statement>
<statement>
...
else:
<else-statement>
...
warning

The break keyword can be used to break a for loop. In such cases, the else part is ignored.

Nested for Loops

For loops can be nested i.e. any for loop can contain within it other for loops.

For example:

for x in range(1, 4):
for y in range(1, 4):
print(f"{x} + {y} = {x+y}")

Output:

1 + 1 = 2
1 + 2 = 3
1 + 3 = 4
2 + 1 = 3
2 + 2 = 4
2 + 3 = 5
3 + 1 = 4
3 + 2 = 5
3 + 3 = 6
note

All Python control structures can be mixed together to the extent necessary (if, for, while, etc.)

Manipulate for loop execution

break statement in for loop

Python break statement is used to exit the loop immediately. It simply jumps out of the for loop and the program continues to execute the code after the loop.

For example, break the loop at yellow

colors = ['red', 'green', 'yellow', 'blue']
for x in colors:
if x == 'yellow':
break
print(x)

Output

red
green

continue statement in for loop

Python continue instruction skips the current iteration of a loop and continues with the next iteration.

For example, continue the loop at yellow

colors = ['red', 'green', 'yellow', 'blue']
for x in colors:
if x == 'yellow':
continue
print(x)

Output

red
green
blue

pass statement in for loop

Python pass statement is a null statement: nothing happens when it is executed.

For example, pass the loop at yellow

colors = ['red', 'green', 'yellow', 'blue']
for x in colors:
if x == 'yellow':
pass
print(x)

Output

red
green
yellow
blue

Examples

Let's look at some examples of frequent situations when programming in python

Numeric Range Loop

To execute a group of statements for a specified number of times, use built-in function range().

The range(start,stop,step) function generates a sequence of numbers from 0 up to (but not including) specified number.

For example, generate a sequence of numbers from 0 to 3


for x in range(4):
print(x)

Output

0
1
2
3
note

The range() method increases by 1 by default.

Three-Expression Loop

The three-expression loop syntax is:

for(i=0; i<=n; i++)
...

but this kind of for loop is not implemented in Python!

However, something similar can be achieved by using numeric range range(start, stop, step)

for i in range(start, stop, step):
...

is equivalent to

for(i=start; i<stop; i=i+step)
...

Collection-Based or Iterator-Based Loop

This type of loop iterates over a set of objects, rather than specifying numeric values or conditions:

for elem in <collection>
...
note

All iterable objects can be iterated in this way.

See the following examples (e.g., the one on the lists) to understand more about them

Iterating a String

Each string can be iterated character by character.

For example:

string = "Tutorial"
for x in string:
print(x)

Output

T
u
t
o
r
i
a
l

Iterating a List

Lists can be iterated with for loop.

For example:

collection = ['a string', 123, 'a', 1.2]
for x in collection:
print(x)

Output

a string
123
a
1.2

Iterating through a Dictionary

You can iterate a dictionary over its keys.

For example:

my_dict = {'key1': 1, 'key2': 2, 'key3': 3}
for key in my_dict:
print(key)

Output

key1
key2
key3

To access dictionary values within the loop, a dictionary reference can be created using the key as usual:

my_dict = {'key1': 1, 'key2': 2, 'key3': 3}
for key in my_dict:
print(my_dict[key])

Output

1
2
3

Loop over Lists of lists

Using nested for loops, you can iterate lists of lists.

For example:

list_of_lists = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]
for list in list_of_lists:
for x in list:
print(x)

Output

1
2
3
4
5
6
7
8
9

Access Index in for Loop

To iterate over the indices of a sequence, you can combine range() and len() methods as follows:

For example:

colors = ['red', 'green', 'blue', 'yellow']
for index in range(len(colors)):
print(index, colors[index])

Output

0 red
1 green
2 blue
3 yellow

However, in most cases it is convenient to use the enumerate() function.

colors = ['red', 'green', 'blue', 'yellow']
for index, value in enumerate(colors):
print(index, value)

Output

0 red
1 green
2 blue
3 yellow

Unpacking in a for loop

If you have a list of tuples, you can unpack the tuples at each iteration using multiple assignment.

For example:

tuple_list = [(1, 2), (3, 4), (5, 6)]
for (x, y) in tuple_list :
print(x, y)

Output

1 2
3 4
5 6