David Raban
David Raban

Reputation: 219

Python logical `and` returning wrong results comparing lists

y1 = [True, True, False, False]
y2 = [False, True, True, False]
y3 = y1 and y2

print(y3)
>>> [False, True, True, False]

What is going on here? the third item in the operation is False and True and this results in True?

Upvotes: 3

Views: 99

Answers (2)

khelwood
khelwood

Reputation: 59112

X and Y evalutes to:

  • X (if X is falsey)
  • Y (if X is truthy)

Any nonempty list is truthy.

So if

y1 = [True, True, False, False]

and

y2 = [False, True, True, False]

then y1 and y2 evaluates to y2, which is [False, True, True, False].

If you want to and individual elements of your lists, you can do it with zip and a list comprehension:

y3 = [x1 and x2 for x1,x2 in zip(y1,y2)]

Upvotes: 5

iacob
iacob

Reputation: 24221

x     | y     | x and y
------|-------|---------
True  | True  | y
True  | False | y
False | True  | x
False | False | x

Since a non-empty list is evaulated as True in a boolean expression in python, x and y returns y.

What you are looking for is:

y3 = [a and b for a,b in zip(y1,y2)]

Upvotes: 0

Related Questions