Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 217
David Raban Avatar asked Jun 26 '26 12:06

David Raban


1 Answers

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)]
like image 151
khelwood Avatar answered Jun 29 '26 01:06

khelwood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!