Python For Loop

Python For loop – In Python, for loop is used when a set of statements are to be executed iteratively over a sequence of elements.

In this tutorial, we will learn the syntax of For Loop, and cover examples with For Loop where For Loop is used to iterate over different types of sequences and collections in Python.

We shall also discuss Nested For Loop in this tutorial.

Syntax – Python For Loop

The syntax of For Loop in Python is

for <variable> in <iterable>:
     statement1
     statement2

where an iterable could be a sequence or collection or any custom Python class object that implements __iter__() method.

Flowchart

The flow of program execution in a Python For Loop is shown in the following picture.

Python For Loop Execution Model - Python Tutorial - www.tutorialkart.com
Flowchart of Python For Loop

For Loop with List

In this example, we will take a list of numbers and use for loop to iterate over each of the element in this list.

example.py – Python Program

myList = [1, 2, 3, 5, 6, 10, 11, 12]

for item in myList:
    print(item)
Try Online

Output

1
2
3
5
6
10
11
12

For Loop with Range

In this example, we will take a range object, and use for loop to iterate over each number in this range.

example.py – Python Program

myRange = range(1, 5)

for number in myRange:
    print(number)
Try Online

Output

1
2
3
4

For loop with String

In this example, we will take a String and use for loop to iterate over each character of the string.

example.py – Python Program

myString = 'tutorialkart'

for ch in myString:
    print(ch)
Try Online

Output

t
u
t
o
r
i
a
l
k
a
r
t

For loop with Tuple

In this example, we will take a tuple and use for loop to iterate over each item in the tuple.

example.py – Python Program

myTuple = ('abc', 'bcd', 'xyz')

for item in myTuple:
    print(item)
Try Online

Output

abc
bcd
xyz

Nested For Loop

Any statement inside the for loop could be another for loop, if block, if-else block or any such.

An example program for nested for loop with embedded if-else blocks is given below.

example.py – Python Program

for greeting in ['hello', 'hi', 'hola']:
    for ch in greeting:
        print(ch)
    if greeting=='hello':
        print("hello buddy!")
    else:
        if greeting=='hi':
            print("hi friend!")
        else:
            print("hola gola!")
Try Online

Output

h
e
l
l
o
hello buddy!
h
i
hi friend!
h
o
l
a
hola gola!

Conclusion

In this Python Tutorial, we have learn about for loop execution flow, for loop syntax in python, nested for loop, for loops that iterate over list, range, string and tuple. As an exercise, try out the for loop that iterates over buffer.