Python For Loop

Python For Loop

Python For Loop can be used to iterate a set of statements once for each item of a sequence or collection.

The sequence or collection could be Range, List, Tuple, Dictionary, Set or a String.

In this tutorial, we will learn how to implement for loop for each of the above said collections. Going forward, we have detailed example programs with Python For Loop.

Syntax – Python For Loop

The syntax of For Loop in Python is

for item in iterable:
    statement(s)

You can access the item variable inside for block. iterable could be a sequence or collection.

Flow Diagram – Python For Loop

The flow chart of Python For Loop is

Python For Loop
Flow Diagram – Python For Loop

When program execution enters for loop for the first time, it checks if there is an item from iterable. If an item is available, the program executes statement(s) inside for block. After execution of the statement(s), the program checks if there is next item available. If True, then the statement(s) are executed again for this next item. The for loop block executes for each item in the iterable. After executing the statement(s) for all items in iterable, the execution comes to a situation where there is no next item in the iterable. At that time, as there is no next item, the for loop is deemed completed, and the execution continues with the next statements in the program.

Example 1: Python For Loop with Range

In this example, we will use a for loop to iterate over a range of numbers.

Python Program

for i in range(25,29):
	print(i)
Run this program

Output

25
26
27
28

The range is from 25 until 29. So, the range has items: 25, 26, 27 and 28. The statements inside the for loop are executed for each of these elements.

For these examples, the body of for loop has only one print statement. But, you may write as many statements as required by following indentation.

Example 2: For Loop with List

In this example, we will take a list and iterate over the items of list using for loop.

Python Program

mylist = ['python', 'programming', 'examples', 'programs']

for x in mylist:
	print(x)
Run this program

Please note that, during each iteration, we are able to access the item for which the loop is running. In this case, we are able to access the item using variable x.

Output

python
programming
examples
programs

Example 3: For Loop with Tuple

In this example, we will take a tuple and iterate over the items of tuple.

Python Program

mytuple = ('python', 'programming', 'examples', 'programs')

for x in mytuple:
	print(x)
Run this program

The same explanation holds here as well. We could access this item of tuple in for loop using variable x.

Output

python
programming
examples
programs

Example 4: For Loop with Dictionary

In this example, we will take a dictionary and iterate over the key:value pairs of the dictionary using for loop.

Python Program

mydictionary = {'name':'python', 'category':'programming', 'topic':'examples'}

for x in mydictionary:
	print(x, ':', mydictionary[x])
Run this program

mydictionary variable returns an iterable to the keys of the dictionary. Therefore, we could get only key into x. But using x as key we are accessing the value from dictionary inside for block.

Output

name : python
category : programming
topic : examples

Example 5: For Loop with Set

In this example, we will take a set of item, and iterate over the each of the items using for loop.

Python Program

myset = {'python', 'programming', 'examples'}

for x in myset:
	print(x)
Run this program

Output

python
examples
programming

As set is an unordered collection, the order in which for loop accesses the next item from the set is not obvious.

Example 6: For Loop with String

String is a collection of characters. As long as we can get an iterable for the object, we can use for loop.

In this example, we will take a string and iterate over the characters using for loop.

Python Program

mystring = 'pythonexamples'

for x in mystring:
	print(x)
Run this program

Output

p
y
t
h
o
n
e
x
a
m
p
l
e
s

Python For Loop – break

From the syntax and flow diagram, we know that for loop will be over only after executing statement(s) for all the elements in the iterable. But, we can break the for loop and end it before it has actually run for all the elements in the iterable using break statement.

In the following program, we shall break the for loop, when the value of element is 7. To realize this, we will use a if statement and execute break statement when the condition evaluates to True.

Python Program

for x in range(2, 10):
    if(x==7):
        break
    print(x)
Run this program

Output

2
3
4
5
6

If there had not been the break statement, for loop would have executed until x is 10.

Python For Loop – continue

We can skip the execution of further statements in the for loop body, during that iteration, using continue statement. When continue statement is executed, the for loop continues with the execution of next element in the iterable, rather than completing all the statements in the for loop body.

In the following example program, we shall continue the for loop, when the value of element is 7.

Python Program

for x in range(2, 10):
    if(x==7):
        continue
    print(x)
Run this program

Output

2
3
4
5
6
8
9

When x is 7, continue statement is executed. The print statement after the continue statement in the for loop has been skipped and continued with the next element in the loop, which is 8.

Python For Loop with Else Block

Just like in an if-else statement, you can use an else block with for loop. This else block is executed after the for loop is completed with all the elements in the iterable.

In the following example, we shall write an else block with for loop.

Python Program

for x in range(2, 6):
    print(x)
else:
    print('Out of for loop')
Run this program

Output

2
3
4
5
Out of for loop

Python Nested For Loop

Python For Loop is just like another Python command or statement. So, can write a for loop inside another for loop and this is called nesting. For loop inside another for loop is called Nested For Loop.

In the following program, we shall write a nested for loop, to print a pattern of numbers to the console.

Python Program

for x in range(5):
    for y in range(6):
        print(x, end=' ')
    print()
Run this program

Output

0 0 0 0 0 0
1 1 1 1 1 1
2 2 2 2 2 2
3 3 3 3 3 3
4 4 4 4 4 4

Summary

In this tutorial of Python Examples, we learned to use Python For Loop on different collections, and with statements like break, continue, else, etc., using well detailed examples.