2

I need help comparing two lists and returning the indices that they don't match.

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

indices 4 and 8 don't match and i need to return that as a list [4,8]

I've tried a few methods but they haven't worked for me.

2
  • 1
    See your question answered already here: stackoverflow.com/questions/35713093/… Commented Apr 7, 2018 at 22:00
  • That will certainly help, but that's not a duplicate, OP wants the indexes not the values. Commented Apr 7, 2018 at 22:03

4 Answers 4

3

Use zip to iterate over both lists at the same time and enumerate to get the indices during iteration, and write a list comprehension that filters out the indices where the list values don't match:

>>> [i for i, (x, y) in enumerate(zip(a, b)) if x != y]
[4, 8]
Sign up to request clarification or add additional context in comments.

4 Comments

PO = [i for i, (x, y) in enumerate(zip(lst1, lst2)) if x!= y] return PO This always returns [0] as my result despite the lists having obvious differences
@dfairch I'm 99.999% sure that this code works correctly. Could you share the two lists you're comparing? (But to be honest I think it's more likely that there's a bug hiding somewhere else in your program.)
lst1 = [0, 1, 1, 0, 0, 0, 1, 0, 1] lst2=[0, 1, 1, 0, 1, 0, 1, 0, 0]
@dfairch That gives [4, 8] as it should. Really, there must be a bug somewhere in your code.
2

You could also just use a simple loop which scans the lists, item by item:

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

diff=[]

for i in range(0,len(a)):
    if a[i]!=b[i]:
        diff.append(i)

print diff

A list comprehension could also do the same thing:

diff=[i for i in range(len(a)) if a[i]!=b[i]]
print diff

1 Comment

range(0,len(a)) could be simplified to just range(len(a))
2

If you are happy to use a 3rd party library, numpy provides one way:

import numpy as np

a = np.array([0, 1, 1, 0, 0, 0, 1, 0, 1])
b = np.array([0, 1, 1, 0, 1, 0, 1, 0, 0])

res = np.where(a != b)[0]

# array([4, 8], dtype=int64)

Relevant: Why NumPy instead of Python lists?

Comments

1

You can use zip :

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

count=0
indices=[]
for i in zip(a,b):
    if i[0]!=i[1]:
        indices.append(count)

    count+=1

print(indices)

output:

[4, 8]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.