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

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

Python For Loop
Flow Diagram – Python For Loop
  1. When program execution enters For loop for the first time, it checks if there is an item from iterable.
  2. If an item is available, go inside the loop, else go to step 3.
    1. Execute the statement(s) inside the For loop block.
    2. Go to step 2.
  3. 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)
Run Code Copy

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)
Run Code Copy

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

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)
Run Code Copy

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

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])
Run Code Copy

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)
Run Code Copy

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)
Run Code Copy

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)
Run Code Copy

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)
Run Code Copy

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')
Run Code Copy

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()
Run Code Copy

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.

Frequently Asked Questions

1. When is For loop used in Python?

Answer:

For Loop is used to execute a block of code for each item in an iterable.

for item in ['apple', 'banana', 'cherry']:
    print(item)
2. What is an example for a For loop in Python?

Answer:

Consider that we are given a list of string items. And our requirement is to print the length of each string in the given list. We can use a For Loop to iterate over the string items in the list, and for each item, we can execute the code that prints the length of the string.

for item in ['apple', 'banana', 'cherry']:
    print(len(item))
3. What is the syntax of For loop in Python?

Answer:

The syntax of For loop in Python is

for item in iterable:
    statement(s)
4. What are the steps in a Python For loop?

Answer:

The steps in a Python For Loop are:

  1. Check if there is an item from iterable.
  2. If an item is available, go inside the loop, else go to step 3.
    1. Execute the statement(s) inside the For loop block.
    2. Go to step 2.
  3. The For loop is marked completed, and the execution continues with the next statements in the program.

for item in iterable:
    statement(s)

Related Tutorials

Code copied to clipboard successfully 👍