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

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)

Explanation

  1. The range(25, 29) function generates numbers starting from 25 and ends before 29.
  2. 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

  1. The for loop iterates over each element in the list my_list, which contains 'apple', 'banana', and 'cherry'.
  2. In each iteration, the variable x holds one element from the list.
  3. The print(x) statement prints the value of x during each iteration.
  4. 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

  1. The for loop iterates over each element in the tuple my_tuple, which contains 'apple' and 25.
  2. In each iteration, the variable x holds one element from the tuple.
  3. In the print(x) statement, x is printed.
  4. 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

  1. The for loop iterates over each key in the dictionary my_dictionary, which contains the keys 'name' and 'category'.
  2. In each iteration, the variable x holds one key from the dictionary.
  3. In the print(x, ':', my_dictionary[x]) statement, x represents the key, and my_dictionary[x] accesses the corresponding value for that key.
  4. 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

  1. The for loop iterates over each element in the set my_set, which contains the items 'apple', 'banana', and 'cherry'.
  2. In each iteration, the variable x holds one element from the set, and print(x) prints it.
  3. 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

  1. The for loop iterates over each character in the string my_string, which is 'apple'.
  2. For each iteration, the variable x holds one character from the string, and print(x) prints it.
  3. Thus, each character of the string is printed on a new line.
  4. 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

  1. The for loop iterates over a range of numbers from 2 to 9 (since range(2, 10) generates numbers from 2 to 9 inclusive).
  2. During each iteration, if the value of x equals 7, the break statement is triggered. This immediately exits the loop, stopping any further iterations.
  3. Thus, the loop stops at 6 and does not print 7 or any numbers after it.
  4. 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

  1. The for loop iterates over a range of numbers from 2 to 9 (since range(2, 10) generates numbers from 2 to 9 inclusive).
  2. During each iteration, if the value of x equals 7, the continue statement is triggered. This skips the rest of the current iteration and moves to the next number in the range.
  3. Thus, the number 7 is skipped in the output, and all other numbers are printed.
  4. 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

  1. The for loop starts iterating from 2 and ends at 5 (since range(2, 6) generates numbers from 2 to 5 inclusive).
  2. In each iteration, the current value of x is printed, which will output: 2, 3, 4, and 5.
  3. Once the loop completes its iterations, the else block is executed, which prints the message 'Out of for loop'.
  4. This else block will always run after the for loop finishes without being interrupted by a break 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

  1. The outer for loop iterates over the range 0 to 4, so it runs 5 times with values of x from 0 to 4.
  2. For each value of x, the inner for loop iterates over the range 0 to 5, so it runs 6 times with values of y from 0 to 5.
  3. In each iteration of the inner loop, the value of x is printed, followed by a space.
  4. After printing 6 times, the print() statement outside the inner loop moves to the next line, creating a new row for each value of x.
  5. As a result, the program prints the value of x six times per row, and this process repeats for x values from 0 to 4, resulting in 5 rows of output with each row containing 6 of the same x 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.




Python Libraries