1

I would like help with the following situation I have two lists:

Situation 1:

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [0, 1, 2, 3, 5, 5, 6, 7, 8, 9]

I need key output: Key 4 is different

Situation 2:

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

I need key output: false -> no key is different

Situation 3:

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [0, 9, 2, 3, 4, 5, 6, 7, 3, 9]

I need key output: Key 1 and Key 8 is different

How could I resolve this? My array has 260 keys

mozway
  • 194,879
  • 13
  • 39
  • 75
  • 1
    Loop through the two arrays using `enumerate()` and `zip()`. If the values are different, append the index to the result list. At the end, print the result list. If it's empty, say that no keys are different. – Barmar Jun 28 '22 at 18:17

3 Answers3

3

You can use a list comprehension with zip, and enumerate to get the indices. Use short-circuiting and the fact that an empty list is falsy to get False:

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [0, 1, 2, 3, 5, 5, 6, 7, 8, 9]

out = [i for i,(e1,e2) in enumerate(zip(a,b)) if e1!=e2] or False

output:

[4]

output for example #2: False

output for example #3: [1, 8]

mozway
  • 194,879
  • 13
  • 39
  • 75
  • @Gustavo that's why I provided the links to the documentation ;) `zip` enables to iterate several iterables in parallel, enumerate enables to get items of an iterable along with their indices. – mozway Jun 28 '22 at 18:28
1

An approach with itertools.compress. Compare the lists to check difference in values, pass the result of the comparison to compress which will pick-up only the True ones.

from itertools import compress

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [0, 1, 2, 3, 5, 5, 6, 7, 8, 9]

result = tuple(compress(a, map(int.__ne__, a, b)))

if not result:
    print(False)
else:
    print(result)
cards
  • 3,936
  • 1
  • 7
  • 25
0

The current answer is really good, but for an approach which doesn't need zip/enumerate, loop like this:

lista = []
listb = []
unequal_keys = []
for idx in range(len(lista)):
    if lista[idx] != listb[idx]:
        unequal_keys.append(idx)

if unequal_keys == []:
    print(False)
else:
    print(unequal_keys)

I recommend learning new techniques and using build ins like zip and enumerate though. They are much more pythonic and faster!

Ariel A
  • 474
  • 4
  • 14