Python for loop

Python for loop tutorial shows how to create loops in Python with for statement.

Loop definition

A loop is a sequence of instructions that is continually repeated until a certain condition is reached. For instance, we have a collection of items and we create a loop to go through all elements of the collection. Loops in Python can be created with for or while statements.

Python for statement

Python for statement iterates over the items of any sequence (such as a list or a string), in the order that they appear in the sequence.

for var in sequence:

The above is the general syntax of the Python for statement.

Python for loop with string

The following example uses Python for statement to go through a string.

word = "cloud"

for let in word:

We have a string defined. With the for loop, we print the letters of the word one by one to the terminal.

$ ./ 

This is the output of the example.

Python for loop else

The for loop has an optional else statement which is executed when the looping has finished.

words = ["cup", "star", "monkey", "bottle", "paper", "door"]

for word in words:

    print("Finished looping")    

We go over the list of words with a for loop. When the iteration is over, we print the "Finished looping" message which is located in the body following the else keyword.

$ ./ 
Finished looping

This is the output of the example.

For loops with range

Python range() function generates a list of numbers.


The function generates numbers 0...n-1.

range(start, stop, [step])

The function generates a sequence of numbers; it begins with start and ends with stop, which is not included in the sequence. The step is the increment and defaults to 1 if not provided.

With the help of the range() function, we can repeat a code block n times.

for i in range(1, 6):
    print("Statement executed {0}".format(i))

The code example executes the code block five times.

$ ./ 
Statement executed 1
Statement executed 2
Statement executed 3
Statement executed 4
Statement executed 5

This is the output.

In the next example we generate two sequences of integers with for loop.

for n in range(1, 11):
    print(n, end=' ')

for n in range(0, 11, 2):
    print(n, end=' ')    

The example prints two sequences of integers: 1, 2, ...10 and 0, 2, ...10.

$ ./ 
1 2 3 4 5 6 7 8 9 10 
0 2 4 6 8 10 

This is the output.

Looping over a tuple and list

With Python for loop, we can easily traverse Python tuples and lists.

nums = (1, 2, 3, 4, 5, 6)   
words = ["cup", "star", "monkey", "bottle"]

for n in nums:
    print(n, end=' ')


for word in words:
    print(word, end=' ')

The code example prints the elements of a tuple and a list.

$ ./ 
1 2 3 4 5 6 
cup star monkey bottle 

This is the output.

Looping with index

Sometimes we need to get the index of the element as well; for this we can use the enumerate() function.

words = ["cup", "star", "monkey", "bottle", "paper", "door"]

for word, idx in enumerate(words):
    print("{0}: {1}".format(word, idx))

With the help of the enumerate() function, we print the element of the list with its index.

$ ./ 
0: cup
1: star
2: monkey
3: bottle
4: paper
5: door

Looping over a dictionary

In the following example, we loop over a Python dictionary.

data = { "de": "Germany", "sk": "Slovakia", "hu": "Hungary", "ru": "Russia" }    

for k, v in data.items():
    print("{0} is an abbreviation for {1}".format(k, v))

The code example prints the keys and the values of the Python dictionary.

$ ./ 
sk is an abbreviation for Slovakia
ru is an abbreviation for Russia
hu is an abbreviation for Hungary
de is an abbreviation for Germany

This is the output.

Python nested for loop

It is possible to nest a for loop into another loop.

nums = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for i in nums:
    for e in i:
        print(e, end=' ')

We have a two-dimensional list of integers. We loop over the elements with two for loops.

$ ./ 
1 2 3 
4 5 6 
7 8 9 

This is the output.

Python for loop with zip

The zip() function creates an iterator from the given iterables.

words1 = ["cup", "bottle", "table", "rock", "apple"]
words2 = ["trousers", "nail", "head", "water", "pen"]

for w1, w2 in zip(words1, words2):
    print(w1, w2)

In the example, we iterate over two lists in one for loop.

$ ./ 
cup trousers
bottle nail
table head
rock water
apple pen

This is the output.

Looping custom iterable

In the next example we loop over a custom iterable.

import random

def myrandom(x):
    i = 0
    while i < x:
        r = random.randint(0, 100)
        yield r
        i = i + 1

for r in myrandom(5):

The code example creates a generator function that yields random integers. With the for loop we generate five random integers.

$ ./ 

This is a sample output.

Python for loop with break

The break statement terminates the for loop.

import random
import itertools 

for i in itertools.count():
   val = random.randint(1, 30)

   if (val == 22):

In the example, we create an endless for loop. We generate and print randon numbers from 1...29. If the generated number equals to 22, the for loop is ended with the break keyword.

$ ./ 

This is a sample output.

Python for loop with continue

The continue keyword is used to interrupt the current cycle, without jumping out of the whole loop. It initiates a new cycle.

num = 0

for num in range(1000):
   num = num + 1
   if (num % 2) == 0:
   print(num, end=' ')

We print all numbers smaller than 1000 that cannot be divided by number 2 without a remainder.

In this tutorial, we have worked with Python for loops.

You might also be interested in the following related tutorials: Python tutorial, Python set tutorial, Python lambda functions, Python list comprehensions, Python map tutorial, Openpyxl tutorial, Python requests tutorial, and Python CSV tutorial.