Python For Loop

Python For loop is an iterator based loop. It is a type of loop that iterates over a list of items through an explicit or implicit iterator.

Python-for-Loop-Syntax

As per for loop documentation syntax of for loop –
Syntax

for  variable in list:
     statements
else:
    statement

NOTE: else statement in for loop is optional and executes when the iterative list is exhausted.
Some example of for loop is as follows

Accessing Python List

Since Python list is a collection of elements and all these elements can be accessed using its index values, thus list items can be accessed using for loop also.

for x in [10,20,30,40,50,60]:
    print(x)
The output of the above code is -
10
20
30
40
50
60

Accessing Python Tuples

for loop for accessing a single element from a tuple

for x in (10,20,30,40,50,60):
    print(x)
The output of the above code is-
10
20
30
40
50
60

Accessing keys from a Python Dictionary

dict1={1:'sunday',2:'monday',3:'Tuesday',4:'wednesday',5:'Thursday',6:'friday',7:'saturday}
for x in dict1:
    print(x)
The output of the above code when executed is as follows
1
2
3
4
5
6
7

with Range( ) function

or for loop can be used using range( ) function like this

for x in range(1,11):
    print(x)
The output of the above code is as follow
1
2
3
4
5
6
7
8
9
10

Nesting of for Loop

For loop can also be nested like while loop and selection statements. The simple syntax of nested for  loop –

for  variable1 in list1:
         for variable2  in list2
                 statement1
          else:
                 statement2
     else:
           statement3

Sample Program to demonstrate the use of nested for loop

for x in range (1,6):
      for y in range(1,x+1):
           print('*', end=" ")
      print()

The output of the above-nested loop-

*
* *
* * *
* * * *
* * * * *

The working of the above code can be better understood if you know how Python Print statement works.

A complete list of Python for Loop exercise with solutions will help you to better understand for loop in Python. The main focus of for loop is the iterative items. Unlike other programming languages for loop in Python does not execute until the associated condition results in true.

  
  
If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.