Python AND operator on two boolean lists – how?

and simply returns either the first or the second operand, based on their truth value. If the first operand is considered false, it is returned, otherwise the other operand is returned.

Lists are considered true when not empty, so both lists are considered true. Their contents don’t play a role here.

Because both lists are not empty, x and y simply returns the second list object; only if x was empty would it be returned instead:

>>> [True, False] and ['foo', 'bar']
['foo', 'bar']
>>> [] and ['foo', 'bar']
[]

See the Truth value testing section in the Python documentation:

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

[…]

  • any empty sequence, for example, '', (), [].

[…]

All other values are considered true — so objects of many types are always true.

(emphasis mine), and the Boolean operations section right below that:

x and y
if x is false, then x, else y

This is a short-circuit operator, so it only evaluates the second argument if the first one is True.

You indeed need to test the values contained in the lists explicitly. You can do so with a list comprehension, as you discovered. You can rewrite it with the zip() function to pair up the values:

[a and b for a, b in zip(x, y)]

Leave a Comment