Python For Loop - Syntax, Examples
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
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
The flow chart of Python For Loop is
- When program execution enters For loop for the first time, it checks if there is an item from iterable.
- If an item is available, go inside the loop, else go to step 3.
- Execute the statement(s) inside the For loop block.
- Go to step 2.
- The For loop is marked completed, and the execution continues with the next statements in the program.
Examples
1. 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)
Explanation
- The
range(25, 29)
function generates numbers starting from 25 and ends before 29. - The
for
loop iterates over these numbers and prints each one on a new line.
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.
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
my_list = ['apple', 'banana', 'cherry']
for x in my_list:
print(x)
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
.
Explanation
- The
for
loop iterates over each element in the listmy_list
, which contains'apple'
,'banana'
, and'cherry'
. - In each iteration, the variable
x
holds one element from the list. - The
print(x)
statement prints the value ofx
during each iteration. - Output:
apple
banana
cherry
Output
apple
banana
cherry
3. For Loop with Tuple
In this example, we will take a tuple and iterate over the items of tuple.
Python Program
my_tuple = ('apple', 25)
for x in my_tuple:
print(x)
Explanation
- The
for
loop iterates over each element in the tuplemy_tuple
, which contains'apple'
and25
. - In each iteration, the variable
x
holds one element from the tuple. - In the
print(x)
statement,x
is printed. - Output:
apple
25
Output
apple
25
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
my_dictionary = {'name':'apple', 'category':'fruits'}
for x in my_dictionary:
print(x, ':', my_dictionary[x])
Explanation
- The
for
loop iterates over each key in the dictionarymy_dictionary
, which contains the keys'name'
and'category'
. - In each iteration, the variable
x
holds one key from the dictionary. - In the
print(x, ':', my_dictionary[x])
statement,x
represents the key, andmy_dictionary[x]
accesses the corresponding value for that key. - Output:
name : apple
category : fruits
my_dictionary 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 : apple
category : fruits
5. For Loop with Set
In this example, we will take a set of strings, and iterate over each of the items in the set using For loop.
Python Program
my_set = {'apple', 'banana', 'cherry'}
for x in my_set:
print(x)
Explanation
- The
for
loop iterates over each element in the setmy_set
, which contains the items'apple'
,'banana'
, and'cherry'
. - In each iteration, the variable
x
holds one element from the set, andprint(x)
prints it. - Since sets are unordered collections, the order of elements printed may vary each time the loop runs.
Output
cherry
banana
apple
As set is an unordered collection, the order in which For loop accesses the next item from the set is not obvious.
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
my_string = 'apple'
for x in my_string:
print(x)
Explanation
- The
for
loop iterates over each character in the stringmy_string
, which is'apple'
. - For each iteration, the variable
x
holds one character from the string, andprint(x)
prints it. - Thus, each character of the string is printed on a new line.
- The output will be:
a
p
p
l
e
Output
a
p
p
l
e
7. break For Loop
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)
Explanation
- The
for
loop iterates over a range of numbers from2
to9
(sincerange(2, 10)
generates numbers from 2 to 9 inclusive). - During each iteration, if the value of
x
equals7
, thebreak
statement is triggered. This immediately exits the loop, stopping any further iterations. - Thus, the loop stops at
6
and does not print7
or any numbers after it. - The output will be:
2 3 4 5 6
.
Output
2
3
4
5
6
If there had not been the break statement, For loop would have executed until x is 10.
8. continue For Loop
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)
Explanation
- The
for
loop iterates over a range of numbers from2
to9
(sincerange(2, 10)
generates numbers from 2 to 9 inclusive). - During each iteration, if the value of
x
equals7
, thecontinue
statement is triggered. This skips the rest of the current iteration and moves to the next number in the range. - Thus, the number
7
is skipped in the output, and all other numbers are printed. - The output will be:
2 3 4 5 6 8 9
.
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
.
9. 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')
Explanation
- The
for
loop starts iterating from2
and ends at5
(sincerange(2, 6)
generates numbers from 2 to 5 inclusive). - In each iteration, the current value of
x
is printed, which will output:2
,3
,4
, and5
. - Once the loop completes its iterations, the
else
block is executed, which prints the message'Out of for loop'
. - This
else
block will always run after thefor
loop finishes without being interrupted by abreak
statement.
Output
2
3
4
5
Out of for loop
Complete tutorial: Python for else
10. Nested For Loop
Python For Loop is just like another Python command or statement. So, we 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()
Explanation
- The outer
for
loop iterates over the range0
to4
, so it runs 5 times with values ofx
from 0 to 4. - For each value of
x
, the innerfor
loop iterates over the range0
to5
, so it runs 6 times with values ofy
from 0 to 5. - In each iteration of the inner loop, the value of
x
is printed, followed by a space. - After printing 6 times, the
print()
statement outside the inner loop moves to the next line, creating a new row for each value ofx
. - As a result, the program prints the value of
x
six times per row, and this process repeats forx
values from 0 to 4, resulting in 5 rows of output with each row containing 6 of the samex
value.
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, we learned to use Python For Loop on different collections, and with statements like break, continue, else block, etc., using well detailed examples.