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

cbrown at cbrownsystems.com cbrown at cbrownsystems.com
Thu Oct 28 19:14:02 CEST 2010


On Oct 28, 10:05 am, Chris Rebert <c... at rebertia.com> wrote:
> On Thu, Oct 28, 2010 at 9:33 AM, cbr... at cbrownsystems.com
>
>
>
> <cbr... at cbrownsystems.com> wrote:
> > On Oct 28, 9:23 am, John Posner <jjpos... at optimum.net> wrote:
> >> On 10/28/2010 12:16 PM, 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
>
> >> > Is there a better pythonic idiom for this situation?
>
> >> Clunky, but it might prompt you to think of a better idea: convert the
> >> lists to sets, and take their intersection.
>
> >> -John
>
> > I thought of that as well, e.g.:
>
> > if set(["monday,"tuesday']).intersection(set(days_off)):
> >    doSomething
>
> > but those extra recasts to set() make it unaesthetic to me; and worse
>
> Why not make days_off a set in the first place? Isn't it,
> conceptually, a set of days off?

That makes sense in my example situation; but often this construct
appears on the fly when the list is a preferred to be a list for other
reasons.

>
> > if not set(["monday,"tuesday']).isdisjoint(set(days_off)):
> >    doSomething
>
> > is bound to confuse most readers.
>
> This way is more straightforward:
>
> if set(["monday", "tuesday"]) & days_off:
>

That's much nicer, even if I have to recast days_off as set(days_off).

Cheers - Chas

> Cheers,
> Chris
> --http://blog.rebertia.com




More information about the Python-list mailing list