Why Does Python Use 'Else' After For and While Loops

Why does python use 'else' after for and while loops?

It's a strange construct even to seasoned Python coders. When used in conjunction with for-loops it basically means "find some item in the iterable, else if none was found do ...". As in:

found_obj = None
for obj in objects:
if obj.key == search_key:
found_obj = obj
break
else:
print('No object found.')

But anytime you see this construct, a better alternative is to either encapsulate the search in a function:

def find_obj(search_key):
for obj in objects:
if obj.key == search_key:
return obj

Or use a list comprehension:

matching_objs = [o for o in objects if o.key == search_key]
if matching_objs:
print('Found {}'.format(matching_objs[0]))
else:
print('No object found.')

It is not semantically equivalent to the other two versions, but works good enough in non-performance critical code where it doesn't matter whether you iterate the whole list or not. Others may disagree, but I personally would avoid ever using the for-else or while-else blocks in production code.

See also [Python-ideas] Summary of for...else threads

What is the use of else after for loop in Python?

From the documentation:

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.

Follow the link for an example how this can be used.

Why is the purpose of the else clause following a for or while loop?

You are wrong about the semantics of for/else. The else clause runs only if the loop completed, for example, if a break statement wasn't encountered.

The typical for/else loop looks like this:

for x in seq:
if cond(x):
break
else:
print "Didn't find an x I liked!"

Think of the "else" as pairing with all of the "if's" in the loop body. Your samples are the same, but with "break" statements in the mix, they are not.

A longer description of the same idea: http://nedbatchelder.com/blog/201110/forelse.html

What is the benefit(s) of having 'else clause' for the while loop in python?

else will not execute if there is a break statement in the loop. From the docs:

The while statement is used for
repeated execution as long as an
expression is true:

while_stmt ::=  "while" expression ":" suite
["else" ":" suite]

This repeatedly tests the expression
and, if it is true, executes the first
suite; if the expression is false
(which may be the first time it is
tested) the suite of the else clause,
if present, is executed and the loop
terminates.

A break statement executed in the
first suite terminates the loop
without executing the else clause’s
suite.
A continue statement executed
in the first suite skips the rest of
the suite and goes back to testing the
expression.

(emphasis mine) This also works for forloops, by the way. It's not often useful, but usually very elegant when it is.


I believe the standard use case is when you are searching through a container to find a value:

for element in container:
if cond(element):
break
else:
# no such element

Notice also that after the loop, element will be defined in the global scope, which is convenient.


I found it counterintuitive until I heard a good explanation from some mailing list:

else suites always execute when a condition has been evaluated to False

So if the condition of a while loop is executed and found false, the loop will stop and the else suite will run. break is different because it exits the loop without testing the condition.

While loop with if/else statement in Python

counter = 1 
while (counter <= 5):
if counter < 2:
print("Less than 2")
elif counter > 4:
print("Greater than 4")
counter += 1

This will do what you want (if less than 2, print this etc.)

Why it skips else block

Because the else for for works similar to that of try. It runs only if the for loop is not broken. From the official document:

When used with a loop, the else clause has more in common with the else clause of a try statement than it does with that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs.

How can I make sense of the `else` clause of Python loops?

The while statement with an else clause

while condition:
suite
else:
exhausted

is exactly equivalent to

while True:
if not condition:
exhausted
break
suite

The for statement with an else clause

for item in iterable:
suite
else:
exhausted

is exactly equivalent to

iterator = iter(iterable)
try:
while True:
item = next(iterator)
suite
except StopIteration:
exhausted

It helps understand the effect of a break or continue statement in the suite statement.

Note. — For the while and for statements without an else clause, replace the exhausted statement with a pass statement in the equivalent code.

To memorise the meaning of the else clause, you can interpret a loop statement as

if loop_breaks:
pass
else:
exhausted


Related Topics



Leave a reply



Submit