Search code examples
pythonany

python any() works differently , why any([1,2]) in [1,3,5] returns True but not any(['a','b']) in ['a','v','x']?


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.??


Solution

  • 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'.