Operations with a Python list operate on the list. list1 and list2
will check if list1
is empty, and return list1
if it is, and list2
if it isn't. list1 + list2
will append list2
to list1
, so you get a new list with len(list1) + len(list2)
elements.
Operators that only make sense when applied element-wise, such as &
, raise a TypeError
, as element-wise operations aren't supported without looping through the elements.
Numpy arrays support element-wise operations. array1 & array2
will calculate the bitwise or for each corresponding element in array1
and array2
. array1 + array2
will calculate the sum for each corresponding element in array1
and array2
.
This does not work for and
and or
.
array1 and array2
is essentially a short-hand for the following code:
if bool(array1):
return array2
else:
return array1
For this you need a good definition of bool(array1)
. For global operations like used on Python lists, the definition is that bool(list) == True
if list
is not empty, and False
if it is empty. For numpy's element-wise operations, there is some disambiguity whether to check if any element evaluates to True
, or all elements evaluate to True
. Because both are arguably correct, numpy doesn't guess and raises a ValueError
when bool()
is (indirectly) called on an array.