for Loop


The for loop in python iterates the block of code for the fixed number of times. It is generally used to traverse the data structures like list, tuple or dictionary.

Syntax:

    for <variable> in <sequence>:
        # statements

Here <variable> is a variable that is used for iterating over the <sequence>. After each iteration, it takes the next value from the <sequence> until the end of sequence is reached.

Example: for loop over list

    myList = [10, “Tutorials”, 20, “Duniya”]
    for i in myList:
        print(i)    

Output:

    10
    Tutorials
    20
    Duniya    


Example: for loop over tuple

    myTuple = [10, “Tutorials”, 20, “Duniya”]
    for i in myTuple:
        print(i)    

Output:

    10
    Tutorials
    20
    Duniya    



Example: for loop over dictionary

    myDictionary = [1:’Tutorials’, 2:’Duniya’]
    for k,v in myDictionary.items():
        print(“key =” + k +” , value =” + v)    

Output:

    key = 1 , value = Tutorials
    key = 2 , value = Duniya    

Example: for loop over string

    for char in “Hello”:
	print(char)

Output:

    H
    e
    l
    l
    o    

Example: Nested for loop

    i, j, n = 0, 0, 4
    for i in range(0,n):	    # generates numbers starting from 0 to n-1
        print()		            # used for next line
        for j in range(0, i+1):
            print(“*”, end=””)



else statement with for loop

Python allows us to use the else statement with for loop which is executed only when all iterations are terminated but if for loop contains any break statement then the else statement will not be executed.

Example:

    for i in range(0,4):
        print(i)
    else:print(“for loop is exhausted”)

Output:

    0
    1
    2
    3    

Example:

    for i in range(0,4):
        print(i)
        break
    else:print(“for loop is exhausted”)
    print(“Loop is broken due to break statement”)

Output:

    0
    Loop is broken due to break statement