Sunday, September 29, 2013

for-else loop in python

This is a very interesting constructor in python and I m quite impressed with this. A very intelligent way to combine a loop with a condition.

Example 1:
foo = [ 1, 2, 3 ]
for i in foo:
    print "inside for loop with value %d"  %(i)
else:
   print "inside else condition %d" %(i)

Output:
inside for loop with value 1
inside for loop with value 2
inside for loop with value 3
inside else condition 3

Example 2:
foo = [ 1, 2, 3 ]
for i in foo:
     if i = = 2:
           print "inside for loop with value %d"  %(i)
           break
else:
   print "inside else condition %d" %(i)

Output:
inside for loop with value 2

Example 3:
foo = [ 1, 2, 3 ]
for i in foo:
     if i = = 2:
           print "inside for loop with value %d"  %(i)
           continue
else:
   print "inside else condition %d" %(i)

Output:
inside for loop with value 2
inside else condition 3

Example 4:
foo = [ 1, 2, 3 ]
for i in foo:
     if i = = 3:
           print "inside for loop with value %d"  %(i)
           break
else:
   print "inside else condition %d" %(i)

Output:
inside for loop with value 3


for-else loop basically means "find some item in the iterable, else if none is found then look into else". In simple words, we can say when for loop gets fully exhausted(i.e; even after looking through all the iterables, if we don't find any item that can make us stop in those iterable item/s) then we should look into else condition. See Example 1 and 3.

If we find a condition in for loop, that can interrupt the for loop and terminate it earlier than it is supposed , then that means we have found something in for loop iterables that we were looking for(see Example 2 and 4), so there is no need to check into else condition.