any([1,2]) in [1,3,5]
output is True
which is right but
any(['a','b']) in ['a','v','x']
gives False
which is wrong ??
why this behavior in python.??
any([1,2]) in [1,3,5]
output is True
which is right but
any(['a','b']) in ['a','v','x']
gives False
which is wrong ??
why this behavior in python.??
They are actually two operations:
first evaluate 'any' and then check if the result is in the other list:
any(list) --> is there any item in the list that is equivalent to True?
any([1, 2]) --> True, any non-zero integer is equivalent to True!
any(['a', 'b']) --> True, any character is equivalent to True!
Then
is the result (True) in [1, 3, 5]? --> Yes! 1 and True are actually the same!
is the result (True) in ['a','v','x']? --> No! True (or 1) is not in the list
You can resolve your problem using 'set':
set([1, 2]) & set([1, 3, 5]) --> set([1]) --> True, any non-empty set is equivalent to True!
set(['a','b']) & set(['a','v','x']) --> set(['a']) --> True, any non-empty set is equivalent to True!
As in the comments, Python makes implicit conversion to bool ('a' --> True) when using 'any' but does exact match (1 is like an internal representation for True) when using 'in'.
any(x)
returns True
if and only if any of the elements of x
evaluate to True
.
So, any([1,2]) in [1,3,5]
first evaluates any([1, 2])
which is True
, since 1
is 'Truthy', and then does True in [1, 3, 5]
.
True in [1, 3, 5]
is True
because in
tests the equality of items with whatever is before the in
. Since, in Python, True == 1
, True
really is in [1, 2, 3]
Therefore any([1,2]) in [1,3,5]
is True
!
So why is the second one False
?
This is because of the difference between 'truthiness' and equivalence.
any(['a', 'b'])
is also True
. Since bool('a') == True
, 'a' is 'truthy'. However, True != 'a'
, so it falls down at the second part, because 'a'
and 'True' are not equivalent That is, True
is not in ['a', 'v', 'b']
.
The correct any usage would be:
>>> any(x in ['a','v','x'] for x in ['a', 'b'])
True
>>> any(x in ['a','v','x'] for x in ['ea', 'b'])
False
You need to check elementwise.
This is being evaluated in 2 parts...
any(['a','b'])
is True
, as is any([1,2])
. So you're really asking python "Is True
in the following list?"
You just happen to get lucky in the first example that 1
is treated by python as equivalent to True
, so as far as it's concerned, True
is in 1, 2, 3
Try... any(1, 2, 3) in (3, 4)
... False. Because 1
isn't in the second list.
You're not using any()
correctly.
any()
takes an iterable, and if any of the values in the iterable are truthy, it returns True, otherwise it returns False.
So, in your first example:
any([1,2]) in [1,3,5]
You're calling any()
on the simple iterable [1,2]
, and any nonzero number is truthy, so any()
returns True
.
True
happens to have an integer value of 1, so your statement is equivalent to 1 in [1,3,5]
, which is true.
You actually wanted this:
any(x in [1,3,5] for x in [1,2])