Comparing two lists for same value

Stack Overflow Asked by Sebaku on November 22, 2020

Let’s say I have 3 lists:

a = [0,0,0,1,1]
b = [1,0,0,0,0]
c = [1,1,1,0,0]


I want to return False whenever there are 1’s at the same position, so for ‘b & c’ it would return False, because they both have a one at index 0, ‘a & b’ and ‘a & c’ should return True in this case.

The way I would do it is:

for i in range(0, len(a)):
if a[i] == 1 and b[i] == 1:
return False
return True


Though I feel this is very inefficient. Is there an easier and more efficient way to do this? I was thinking of using binary AND, but not sure how to implement that.

Are you looking for one liner. Here it is:

any([False if a[i] == 1 and b[i] == 1 else True for i in range(0, len(a))])

Sorry did not test it. Here is modified version with test:

>>> a = [0,0,0,1,1]
>>> b = [1,0,0,0,0]
>>> c = [1,1,1,0,0]
>>> def f(a,b):
...   return all([False if a[i] == 1 and b[i] == 1 else True for i in range(0, len(a))])
...
>>> print(f(a,b), f(b,c), f(a,c))
True False True


Answered by Aaj Kaal on November 22, 2020

Related Questions

Remove item from state

3  Asked on December 5, 2020 by clayton-crockville

How to create two different Menu in one page for different type of user in HTML using PHP and CSS

1  Asked on December 5, 2020 by gympotato

A simple IF statement in Python 3.X Pandas not working

2  Asked on December 5, 2020 by ram

How to concatenate 3 lists even if there are a list null?

2  Asked on December 5, 2020 by alexz

Angular 8: Select first element of ng-content

1  Asked on December 5, 2020 by ijustdev

docker-compose volume empty

3  Asked on December 5, 2020 by kerby82

Trying to remove suffix from string with no success

4  Asked on December 5, 2020 by user273283

Extract value of column from a line (variable)

4  Asked on December 4, 2020 by user4516211

Sequelize – N:M Association Count Number of Included Model with Condition

1  Asked on December 4, 2020 by cylee

Include device location and multiple map markers in camera bounds

1  Asked on December 4, 2020 by orbit

How to generalize a code for exporting DataGridView to Excel file?

2  Asked on December 4, 2020

Merge Two Files in Weka based on date

1  Asked on December 4, 2020 by spwath

Gorilla Mux Router GET URL with multiple query param only matches if called by all query params

0  Asked on December 4, 2020 by sumit-arora

Set Session ID Cookie in Nuxt Auth

1  Asked on December 4, 2020 by dominooch

Exo player add raise/send analytics event total time spent

2  Asked on December 4, 2020 by alphanso

Why are arrow functions as static members values not lexically scoped?

1  Asked on December 3, 2020 by zerkms

Undefined error after webservice .asmx returns successful json data

0  Asked on December 3, 2020 by ookie

Debugging an Expo project with Attach to Debugger option throws t.RawDebugSession.handleErrorResponse error after a while or saving changes

0  Asked on December 3, 2020 by nostromo