Compare two lists elementwise with OR

37 views Asked by At

I want to compare two lists of the same length by their elements with an OR.

>>> [0,0,1,1,0] or [1,1,0,1,0]
[0, 0, 1, 1, 0]

I want the outcome to be

[1,1,1,1,0]

How can I achieve the desired comparison?

3

There are 3 answers

0
TheHungryCub On BEST ANSWER

You can use zip() function is used to iterate over corresponding elements of both lists simultaneously, and then a list comprehension is used to perform the OR operation on each pair of elements.

list1 = [0, 0, 1, 1, 0]
list2 = [1, 1, 0, 1, 0]

result = [a or b for a, b in zip(list1, list2)]
print(result)

Output:

[1, 1, 1, 1, 0]
1
Lfppfs On

Use numpy:


import numpy as np

np.logical_or([0,0,1,1,0], [1,1,0,1,0]).astype(int)
array([1, 1, 1, 1, 0])

And check the answers to this question:

Python list of booleans comparison gives strange results

0
Suramuthu R On
l1 = [0,0,1,1,0]
l2 = [1,1,0,1,0]

l = [1 if l1[i] == 1 or l2[i] == 1 else 0 for i in range(len(l1))]
print(l) #Output : [1, 1, 1, 1, 0]

# without using one-liner
l = []
for i in range(len(l1)):
    if l1[i] == 1 or l2[i] == 1:
        l.append(1)
    else: l.append(0)
print(l)