for: else: - any practical uses for the else clause?

BJörn Lindqvist bjourne at gmail.com
Fri Sep 29 17:32:42 EDT 2006


On 9/29/06, Johan Steyn <johan.steyn at gmail.com> wrote:
>  I agree that it is meaningless without a break statement, but I still find
> it useful when I want to determine whether I looped over the whole list or
> not. For example, if I want to see whether or not a list contains an odd
> number:
>
>  for i in list:
>      if i % 2 == 1:
>          print "Found an odd number."
>          break
>  else:
>      print "No odd number found."
>
>  Without the else clause I would need to use an extra variable as a "flag"
> and check its value outside the loop:

You can use generator comprehension:

if (i for i in list if i % 2 == 1):
    print "Found an odd number."
else:
    print "No odd number found."

I *think* any() should also work:

if any(i % 2 == 1 in list):
    ....

And so on. For every use of the for/else clause there exists a better
alternative. Which sums up my opinion about the construct -- if you
are using it, there's something wrong with your code.

-- 
mvh Björn



More information about the Python-list mailing list