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

4
  • 2
    You're not checking if 1 is in each of them. You're checking if 1 is equal to x, y or z. That's what in (x, y, z) means. Commented Jun 27, 2020 at 23:39
  • @khelwood thank you! but when i do if 1 in x it also prints passed, why would that be? Commented Jun 27, 2020 at 23:46
  • 1
    x contains three ints, one of which is 1, so 1 in x is true. (x,y,z) contains three lists, not ints, so 1 in (x,y,z) is false. Commented Jun 27, 2020 at 23:48
  • Oh I think I get it now. if 1 in . . . will check each item, so in the case I put (x,y,z) it checks each list but for the y variable even though it has 1, it is seen as [1] which is not exactly 1.. But it does pass the flag if only one variable is listed at a time because it checks each item in the list? Thank you! Commented Jun 27, 2020 at 23:55

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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')

Comments

0

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...")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.