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

John Nagle nagle at animats.com
Fri Oct 29 07:24:40 CEST 2010


On 10/28/2010 9:23 AM, John Posner wrote:
> On 10/28/2010 12:16 PM, cbrown 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

    d1 = set('monday','tuesday')
    days_off = set('saturday','sunday')

    if not d1.isdisjoint(days_off) :
	...

    This is cheaper than intersection, since it doesn't have to allocate 
and construct a set. It just tests whether any element in the smaller of 
the two sets is in the larger one.

					John Nagle




More information about the Python-list mailing list