ewe
ewe

Reputation: 159

Testing multiple flags python

x = [1,2,3]
y = [1]
z = [0, 1, False]

if 1 in (x, y, z):
    print('passed')

Why does this code not print passed? Since 1 is in each of them shouldn't it print passed? When I put only one of the variables it does print passed though.

Upvotes: 0

Views: 894

Answers (3)

Nick
Nick

Reputation: 147166

Your code is checking whether 1 is equal to x or y or z (which it is not, since they are all lists and 1 is a number). What you want to do instead is check if 1 is in all of the lists:

x = [1,2,3]
y = [1]
z = [0, 1, False]
if all(1 in l for l in (x, y, z)):
    print('passed')

Output:

passed

Upvotes: 1

Mr. lindroid
Mr. lindroid

Reputation: 191

In your code,

if 1 in (x, y, z):

checks 1 in ([1, 2, 3], [1], [0,1,False]) In the condition its like ( [list1], [list2], [list3] ) So its checking, is list1, list2 or list3 is equal to 1 or not!

So the full condition is look like this:

[1, 2, 3] = 1 # False

[1] = 1 # False

[0, 1, False] = 1 #False

As you can see everything is false, during the if statement.

Use this simple syntex instead :

if (1 in x) or (1 in y) or (1 in z):
     print ("passed...")

Upvotes: 0

Ghost
Ghost

Reputation: 735

If you want to check if 1 is in each of them then you can do

if 1 in x and 1 in y and 1 in z:
    print('passed')

Upvotes: 0

Related Questions