Pythonic way of saying 'at least one of a, b, or c is in some_list'

cbrown at cbrownsystems.com cbrown at cbrownsystems.com
Fri Oct 29 03:02:52 EDT 2010


On Oct 28, 11:56 am, Arnaud Delobelle <arno... at gmail.com> wrote:
> "cbr... at cbrownsystems.com" <cbr... at cbrownsystems.com> writes:
> > It's clear but tedious to write:
>
> > if 'monday" in days_off or "tuesday" in days_off:
> >     doSomething
>
> > I currently am tending to write:
>
> > if any([d for d in ['monday', 'tuesday'] if d in days_off]):
> >     doSomething
>
> > Is there a better pythonic idiom for this situation?
>
> The latter can be written more concisely:
>
>     if any(d in days_off for d in ['monday', 'tuesday']):
>         # do something
>

For the list comprehension approach, I like this much better. In the
situation I am thinking of, it very naturally reads as 'if any of my
days off is monday or tuesday', rather than the logically equivalent,
but somewhat convoluted 'if any of monday or tuesday is one of my days
off'.

I should note that efficiency is not an issue to me here; this is for
when you have, say, a list user_options of at most around 15 options
or so, and you want to perform some action if one or more of a, b, or
c is an option listed in user_options. Big O notation isn't so
relevant as readability and 'naturalness'.

Cheers - Chas



More information about the Python-list mailing list