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 12:34:46 EDT 2010


On Oct 29, 2:43 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Thu, 28 Oct 2010 09:16:42 -0700, cbr... at cbrownsystems.com wrote:
> > 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
>
> Use a simple generator expression and any.
>
> if any(day in days_off for day in ['monday', 'tuesday']):
>     doSomething
>
> You (partially) defeat the short-circuiting behaviour of any() by using a
> list comprehension.
>

Good point, thanks.

> If you have a lot of items to test against, make days_off a set instead
> of a list, which makes each `in` test O(1) instead of O(N). For small N,
> the overhead of creating the set is probably going to be bigger than the
> saving, so stick to a list.
>
> Other than that, doing set operations is overkill -- it obfuscates the
> intention of the code for very little gain, and possibly negative gain.
> And as for the suggestion that you create a helper class to do the work,
> that's surely the recommended way to do it in Java rather than Python.
>

Agreed. In the situation I am thinking of, N is generally very small,
and readability trumps execution speed.

Cheers - Chas


> --
> Steven




More information about the Python-list mailing list