Reputation: 47
I have two lists of Bools in python:
l1 = [True, False, True]
l2 = [False, True, True]
And I wish to do elemental-wise comparison And/Or for them. I wish to get:
l3 = [False, False, True] # elemental-wise And
l4 = [True, True, True] # elemental-wise Or
So I simply put:
l3 = l1 and l2
l4 = l1 or l2
But the result behaves unexpectedly as:
l3=[False, True, True] (which is l2)
l4=[True, False, True] (which is l1)
How can I accomplish the elemental-wise comparison nice and clean?
Upvotes: 2
Views: 107
Reputation: 9047
You can use list comprehension
l3 = [(i and j) for i,j in zip(l1,l2)]
l4 = [(i or j) for i,j in zip(l1,l2)]
When you are doing
l3 = l1 and l2
l4 = l1 or l2
then it is getting reduced to
l3 = bool(l1) and l2
l4 = bool(l1) or l2
Now since l1
is non-empty list, so
bool(l1) = True
Now, what I assume in the case of l3 = l1 and l2
, l1
is evaluated as True
so for short circuit evaluation
, it returns l2
.
In case of l4 = l1 or l2
, again due to short circuit evaluation
, l1
is returned since l1
is True
.
So, you are getting the result like that.
short circuit evaluation
is nothing but--
A and B
, if A evaluates to True go on evaluating B and return the result of B. If A evaluates to False, then no point of evaluating B. Return the result of A.False and print('hello')
>>> False
True and print('hello')
>>> hello
A or B
, if A evaluates to True, then there is no point in evaluating B. Just return the result of A. If A evaluates to False, then return the result of B.True or (1/0)
>>> True
False or (1/0)
>>> ZeroDivisionError: division by zero
Note:
bool([]) = False
bool([1,2,'a']) = True
bool(['False']) = True
Upvotes: 3
Reputation: 27567
You can use the built-in all()
and any()
methods in a list comprehension:
l1 = [True, False, True]
l2 = [False, True, True]
l3 = [all(z) for z in zip(l1, l2)]
l4 = [any(z) for z in zip(l1, l2)]
print(l3)
print(l4)
Output
[False, False, True]
[True, True, True]
You can also use the built-in map()
method:
l1 = [True, False, True]
l2 = [False, True, True]
l3 = map(all, zip(l1, l2))
l4 = map(any, zip(l1, l2))
print(list(l3))
print(list(l4))
Output:
[False, False, True]
[True, True, True]
Upvotes: 2