Python for loop-Explained with Examples

Good programmers never repeat their code.Repeating and Rewriting same code again and again is bad programming habit.programmers should reuse their code in order to optimize the performance of the code,and loops can be used to implement re-usability in our code.Python provides loops like while loop,for loop and do-while loop,In this tutorial you will learn about for loop in python with example and you will also learn about break and continue keyword in python.

For loopBasic

Execution of same block of code again and again is called iteration.For loop is used when we know ,how many times we want to repeat our code.This is called definite iteration.

for [var] in [iterators|limit|range]:
    [ do something ]

Let’s see how we can use python “for” loop in different ways.

Python for loop with numbers

We can use for loop with numbers.Syntax for using for loop with numbers is below:

for i in range(n):
    [ do something ]

Here,i is a variable that is used to iterate over values in the list which is generated by range function.Next,in next line we can do anything we want.

for i in range(5):
    print(i)

Above code will run 5 times and will print 0,1,2,3,4 as range(5) will generate a list of 5 numbers from 0 to 4.

Using for loop with list

We can use for loop directly with list because list’s are iterable items.List can contain any object type like numbers,characters,functions and list’s too.Syntax for using for loop with list is below:

for i in list:
   [ do something ]

Lets look at some examples:

###for loop with list containing numbers

a=[1,2,3,4,5]
for i in a:
    print(i) ##prints 1,2,3,4,5
###for loop with list containing float

a=[1.0,2.0,3.0,4.0,5.0]
for i in a:
    print(i) ## prints 1.0,2.0,3.0,4.0,5.0


###for loop with list containing functions

def a():
    print(a)

def b():
    print(b)

func=[a,b] ##list of functions a and b

for i in func:
    print(i)
##OUTPUT##
##<function a at 0x7fd6076500e0>
##<function b at 0x7fd607650290>


###for loop with list containing list

a=[1,2]
b=[3,4]
c=[a,b]

for i in c:
    print(i)

##OUTPUT##
[1, 2]
[3, 4]

for loop with python dictionaries

for loop can be used with python dictionaries.With dictionaries,for loop iterates over the keys of dictionaries.

a={'a':1,'b':2,'c':3,'d':4,'e':5}
for i in a:
    print(i) 

Above code will print a,b,c,d,e which are keys of dictionaries.To print keys with their values we need to write the code in following ways.

a={'a':1,'b':2,'c':3,'d':4,'e':5}
for i in a:
    print(a[i]) 
##OUTPUT##
#1,2,3,4,5

As we can access dictionaries key value as name_of_dictionary[key],same we have done in code above.As we are iterating over keys using for loop and keys are stored in variable i,we are accessing elements of dictionary using a[i].

Another way of accessing key,value of dictionary is using .item() method which return key,value pairs of dictionary as a tuple.

a={'a':1,'b':2,'c':3,'d':4,'e':5}
for i,v in a.items():
    print(i,v) 

##OUTPUT##
a 1
b 2
c 3
d 4
e 5

for loop with strings

In python,strings are also iterables,hence we can use for loop with strings also.Syntax of using for loop with strings is:

for var in string:
    [ do something ]
String="Hello ! This is for loop tutorial"

for i in String:
    print(i)

Above code will print each character of the string.

Changing behaviour of for loop

for loop iterates over all the elements in an iterator till it exhausts.But,sometime we want to skip some element which matches our condition or do something with the elements which matches a certain condition.

In below code,range function will generate numbers from 1 to 10.Suppose I want to print only numbers which are completely divisible by 2(even),then I can check the condition inside for loop.

a=range(1,11)

for i in a:
    if i%2==0:
        print(i)
    else:
        continue

##OUTPUT##
2,4,6,8,10

In above code I am checking,whether remainder of division is 0 or not by using %(modulus) operator.If remainder is 0,means number is completely divisible and print it.If number is not divisible by 2,that condition is written in else block.continue is python keyword which skips the current iteration and continues with next iteration.Note that,continue is different than break keyword.

break keyword breaks the loop and come out of it without executing the next commands.

a=range(1,11)

for i in a:
    if i%2==0:
        break
    else:
        print(i)

##OUTPUT##
1

The above code printed 1 and skipped other numbers,because in first iteration,when i=1,if condition does not matched and it moved to else block where it printed value of i which is 1.In next iteration,when i=2,i%2 is 0 and if condition is matched and it executed break statement.Due to break statement,loop breaks and comes out of the loop.

So,this is the end of for loop tutorials.In this tutorial,you learned about python for loop,how to use for loop with other python objects,continue and break keywords.If you have any doubt or any suggestion,feel free to comment below.

Thank You.

Amarjeet

About Amarjeet

Amarjeet,BE in CS ,love to code in python and passionate about Machine Learning and Data Science. Expertsteaching.com is just a medium to share what I have learned till now with world.
Bookmark the permalink.

One Comment

  1. Pingback: While Loop-Python - ExpertsTeaching

Leave a Reply

Your email address will not be published. Required fields are marked *