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.

Update (Dec 21, 2017): I guess I could simply summarize the for-ELSE loop as for-NoBreak loop. I mean when no BREAK is encounter in for loop, then only ELSE condition gets executed.

Update (Oct 12, 2020): Food for thoughts:
arr = [1, 2, 3, 4]
Question 1:
def f():
    for i in arr:
        if i == 4:
            break
        print(i, end=' ')
    else:
        print("else part")
Output: 1 2 3

Question 2:
def f():
    for i  in arr:
        pass
    else:
        print("else part")
Output: else