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.

miradulo
  • 28,857
  • 6
  • 80
  • 93
dfairch
  • 29
  • 1
  • 1
    See your question answered already here: https://stackoverflow.com/questions/35713093/how-can-i-compare-two-lists-in-python-and-return-not-matches – Idodo Apr 07 '18 at 22:00
  • That will certainly help, but that's not a duplicate, OP wants the indexes not the values. – progmatico Apr 07 '18 at 22:03

4 Answers4

4

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]
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • 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 Apr 07 '18 at 22:04
  • @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.) – Aran-Fey Apr 07 '18 at 22:05
  • lst1 = [0, 1, 1, 0, 0, 0, 1, 0, 1] lst2=[0, 1, 1, 0, 1, 0, 1, 0, 0] – dfairch Apr 07 '18 at 22:33
  • 1
    @dfairch That gives `[4, 8]` as it should. Really, there must be a bug somewhere in your code. – Aran-Fey Apr 07 '18 at 22:35
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
Peter Ye
  • 457
  • 2
  • 6
  • 17
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?

jpp
  • 159,742
  • 34
  • 281
  • 339
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]
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88