Reputation: 5534
So I'm looking for a shorthand way of doing this:
if a == 5 or a == 6 or a == 7:
And having it be something like this:
if a == (5 or 6 or 7):
Now, I know I could do this:
if a in [5,6,7]:
But I'm looking for something more general that would work when the elements can't be easily put into a list (for instance if they are long variable names or if each element is itself a list)
I'm also aware of the any()
function, but that doesn't clean it up much (I still have to have a ==
for each condition).
Can this be done and what is the correct syntax?
EDIT: I know this can be done simply with a bunch of methods, but I'm asking specifically about chaining comparisons together as shown in the second snipit
Upvotes: 0
Views: 228
Reputation: 28292
Generally, you can always use the in
operator for this. If you want to find something inside a nested list, you can always use itertools.chain.from_iterable
. To be honest, right now i couldn't think a case when we couldn't use lists.
For example:
>>> my_list = [[1,2,3],[4,5,6], 6, 7, 2, 3, 'abc']
>>> n = 5
>>> n in itertools.chain.from_iterable(my_list)
True
>>>
>>> s = 'a' #You can even find if a char exists in the list
>>> s in itertools.chain.from_iterable(my_list)
True
And the answer for your question, do something like in the second snippet? No.
Upvotes: 1
Reputation: 11561
The pythonic way is
if a in (5, 6, 7):
if a in [5, 6, 7]:
The first is also correct:
if a == 5 or a == 6 or a == 7:
The second statement does not do what you think it does:
bool(6 == (5 or 6 or 7))
Out[1]: False
Upvotes: 0
Reputation: 168696
The commonly recommended syntax for this is x in <list>
, as you've described.
if a in [5,6,7]:
The cases which you claim aren't appropriate work equally well:
# Long names
if a in [the_first_of_november,
the_second_sunday_in_the_third_lunar_month,
tuesday]:
# Lists:
if myList in [yourList, hisList, herList]:
In my opionion, the clearest use of in
involves pre-computing the right-hand list:
if my_answer in list_of_correct_answers:
If you are able to construct the list elsewhere, this is perfectly readable for every case you've mentioned.
Upvotes: 2