Pythonic way of saying 'at least one of a, b, or c is in some_list'
steve at REMOVE-THIS-cybersource.com.au
Fri Oct 29 11:43:48 CEST 2010
On Thu, 28 Oct 2010 09:16:42 -0700, cbrown at cbrownsystems.com wrote:
> It's clear but tedious to write:
> if 'monday" in days_off or "tuesday" in days_off:
> I currently am tending to write:
> if any([d for d in ['monday', 'tuesday'] if d in days_off]):
Use a simple generator expression and any.
if any(day in days_off for day in ['monday', 'tuesday']):
You (partially) defeat the short-circuiting behaviour of any() by using a
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.
More information about the Python-list