Home > Blockchain >  Python's any() function on a list of lists gives weird outputs
Python's any() function on a list of lists gives weird outputs

Time:01-24

Given a list of lists named a, I got the following outputs on exploration of the any() function. It would be great if I could get some help in understanding the logic behind these outputs. Why are some outputs True and some False, even though all should be True?

a = [[1,2,3], [0,3,6], 5, [4,5,7], [0,1,2]]

print(any(a) in [0,3,4,[5],100])
print(any(a) in [1,2,3,4,5])     # Gives True
print(any(a) in [4,5,7,6])       # Gives False
print(any(a) in [0,1,2,4])       # Gives True
print(any(a) in [5])             # Gives False

CodePudding user response:

Your syntax is wrong. You are first computing any(a) (which is True) then check if True is in your target list. The reason it sometimes returns True is the fact that int(True) is equal to 1, so it only prints True if your target list contains a 1.

Try this, for example:

print(any(x in [4,5,7,6] for x in a))     # Should print True

CodePudding user response:

Actually it is not the functioning of any but instead the functioning of in operator in python.

Basically in works in the following way :-

for i in iterable:
    if i == value:
        return True
else:
    return False

Now if you apply this logic manually over one of your conditions that return True, you can find the element which causes this peculiar behaviour:-

for i in [1,2,3,4,5]:
    if i == True: # Since any(a) is True
        print(i)

and the output this produces is :-

1

Thus, one thing which you can infer from this is that the integer 1 represents the boolean True also, which you can confirm by checking in the interactive shell :-

Boolean Check

Thus, you can observe that in python the integers 0 and 1 represent the booleans False and True respectively, too.

Therefore, now you can understand why your code executes in a peculiar way, like this...

a = [[1,2,3], [0,3,6], 5, [4,5,7], [0,1,2]]

print(any(a) in [0,3,4,[5],100]) # Will give False because 1 is NOT present
print(any(a) in [1,2,3,4,5])     # Gives True because 1 is present
print(any(a) in [4,5,7,6])       # Gives False because 1 is NOT present
print(any(a) in [0,1,2,4])       # Gives True because 1 is present
print(any(a) in [5])             # Gives False because 1 is NOT present
  •  Tags:  
  • Related