empty clause of for loops

Random832 random832 at fastmail.com
Wed Mar 16 13:08:54 EDT 2016


On Wed, Mar 16, 2016, at 13:01, Sven R. Kunze wrote:
> On 16.03.2016 17:56, Sven R. Kunze wrote:
> > On 16.03.2016 17:37, Random832 wrote:
> >> for item in collection:
> >>     if good(item):
> >>        thing = item
> >>        break
> >> else:
> >>     thing = default # or raise an exception, etc
> >
> > I was thinking about why we don't use it that often. My response to 
> > this example:
> >
> > thing = item if item in collection else default
> 
> Time for a break. That is not going to work.
> 
> Will still think about why we don't use it (often/at all).

Yeah, well, you can *almost* get there with:

try:
    thing = next(item for item in collection if good(item))
except StopIteration:
    thing = default

But the for/else thing seems like a more natural way to do it. Plus,
this is a toy example, if the body is more than one statement or doesn't
involve returning a value comprehensions aren't a good fit.



More information about the Python-list mailing list