

What else is there in Python? - Nurdok
http://blog.amir.rachum.com/post/27860231695/what-else-is-there-in-python

======
dudus
I agree that the use of else on for and while clauses is very not intuitive.
It would be far better if the else would be executed if the list you're
iterating over is empty and thus the for/while clause is never ran not even
once.

So you could rewrite:

    
    
        last_val = None
        for item in myList:
          last_val = item
    

to:

    
    
        for item in myList:
          last_val = item
        else: 
          last_val = None

~~~
ggchappell
Yes, "else" is a strange keyword to use for it, but I have found the
_existing_ semantics to be useful in practice. The application is nearly
always related to handling success/failure of some kind of search. In Python,
for..else allows elimination of variables whose names are something like
"found".

In C++:

    
    
      bool found = false;
      for (...)    // Look for something
      {
         XXX;
         if (YYY)
         {
             found = true;
             break;
         }
      }
      if (!found)  // Didn't find it
      {
          ZZZ;
      }
    

but in Python:

    
    
      for ...:  # Look for something
          XXX
          if YYY: break
      else:     # Didn't find it
          ZZZ

