Python for Loop

The for statement in Python is a bit different from what you usually use in other programming languages.

Rather than iterating over a numeric progression, Python’s for statement iterates over the items of any iterable (list, tuple, dictionary, set, or string)

The items are iterated in the order that they appear in the iterable.

Syntax

Here’s the syntax of the for statement:

Python for Loop Syntax

Basic Examples

Example: Iterate through a list

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

Example: Iterate through a string

S = 'python'
for x in S:
    print(x)
# p y t h o n

Break in for Loop

Python break statement is used to exit the loop immediately.

It simply jumps out of the loop altogether, and the program continues after the loop.

Example: Break the loop at ‘blue’

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

Continue in for Loop

The continue statement skips the current iteration of a loop and continues with the next iteration.

Example: Skip ‘blue’

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

Else in for Loop

Python allows an optional else clause at the end of a for loop.

The else clause will be executed if the loop terminates naturally (through exhaustion).

Example: else clause is executed when loop terminates naturally

colors = ['red', 'green', 'blue', 'yellow']
for x in colors:
    print(x)
else:
    print('Done!')
# red green blue yellow
# Done!

If the loop terminates prematurely with break, the else clause won’t be executed.

Example: else clause is not executed when loop terminates prematurely

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

range() function in for loop

If you need to execute a group of statements for a specified number of times, use built-in function range()

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

Example: Generate a sequence of numbers from 0 6

for x in range(7):
    print(x)
# 0 1 2 3 4 5 6

range() provides a simple way to repeat an action a specific number of times.

Example: Print ‘Hello!’ three times

for x in range(3):
    print('Hello!')
# Hello!
# Hello!
# Hello!

The range starts from 0 by default. But, you can start the range at another number by specifying start parameter.

Example: Generate a sequence of numbers from 2 to 6

for x in range(2, 7):
    print(x)
# 2 3 4 5 6

You can generate a range of negative numbers as well.

Example: Generate a sequence of negative numbers

for x in range(-5,0):
    print(x)
# -5 -4 -3 -2 -1

The range increments by 1 (by default). But, you can specify a different increment by adding a step parameter.

Example: Increment the range() with 2

for x in range(2, 7, 2):
    print(x)
# 2 4 6

Nested for Loop

A loop inside another loop is called a nested loop.

Example: Iterate a nested list

list = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]   
for sublist in list:
    for number in sublist:
        print(number)
# 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() as follows:

Example: Access index in for loop with range() and len()

colors = ['red', 'green', 'blue']
for index in range(len(colors)):
    print(index, colors[index])
# 0 red
# 1 green
# 2 blue

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

Example: Access index in for loop with enumerate()

colors = ['red', 'green', 'blue']
for index, value in enumerate(colors):
    print(index, value)
# 0 red
# 1 green
# 2 blue

Unpacking in a for loop

Below for loop does a multiple assignment (unpack the current tuple) each time through the loop.

Example: Tuple unpacking in for loop

T = [(1, 2), (3, 4), (5, 6)]
for (a, b) in T:
    print(a, b)
# 1 2
# 3 4
# 5 6

Likewise, you can iterate through both keys and values in a dictionary.

Example: Dictionary unpacking in for loop

D = {'name': 'Bob', 'age': 25}
for x, y in D.items():
	print(x, y)
# age 25
# name Bob

Modify List While Iterating

Don’t alter mutable objects while looping on them. It may create an infinite loop.

Example:

# infinite loop
colors = ['red', 'green', 'blue']
for x in colors:
    if x == 'red':
        colors.insert(0, 'orange')
        print(colors)

It is recommended that you first make a copy. The slicing operator makes this especially convenient.

Example:

colors = ['red', 'green', 'blue']
for x in colors[:]:
	if x == 'red':
		colors.insert(0, 'orange')
print(colors)
# ['orange', 'red', 'green', 'blue']

Looping Through Multiple Lists

Using built-in zip() function you can loop through multiple lists at once.

Example: Loop through two lists at once

name = ['Bob', 'Sam', 'Max']
age = [25, 35, 30]
for x, y in zip(name, age):
    print(x, y)
# Bob 25
# Sam 35
# Max 30