user366121
user366121

Reputation: 3271

python find differing elements in list

I want to compare lists of this kind:

A = [0,1,0,1,0,1,0,0,0,1,0,1,0,1,0]
B = [0,1,0,1,0,0,0,1,0,1,0,1,0,1,0]

and find out what elements differ. In this case it should return index 5 of A and index 7 of B. All the other elements are the same. Is there a function for this?

best, US

Upvotes: 2

Views: 254

Answers (4)

Tadeck
Tadeck

Reputation: 137360

Something like that should do the trick (untested):

[i for i, v in enumerate(zip(A, B)) if sum(v) == 1]

This will return list of numbers of elements that have different values in each list.

If your data set is different than in the question, then you could use this:

[i for i, v in enumerate(zip(A, B)) if v[0] != v[1]]

Upvotes: 1

Lee Netherton
Lee Netherton

Reputation: 22512

Another (perhaps more readable?) one-liner:

>>> [index for (index,(a,b)) in enumerate(zip(A,B)) if a!=b]
[5, 7]

This first zips the lists together:

[(0, 0), (1, 1), (0, 0), (1, 1), (0, 0), (1, 0), (0, 0), (0, 1), (0, 0), 
(1, 1), (0, 0), (1, 1), (0, 0), (1, 1), (0, 0)]

And then attaches an index to the items with the enumerate() function:

[(0, (0, 0)), (1, (1, 1)), (2, (0, 0)), (3, (1, 1)), (4, (0, 0)), (5, (1, 0)), 
(6, (0, 0)), (7, (0, 1)), (8, (0, 0)), (9, (1, 1)), (10, (0, 0)), (11, (1, 1)), 
(12, (0, 0)), (13, (1, 1)), (14, (0, 0))]

It then uses a fairly standard list comprehension to compare the items an builds a list of indices where the items do not match.

Upvotes: 1

Abhranil Das
Abhranil Das

Reputation: 5918

Do you necessarily want a one-liner? Because otherwise there's more simple code:

for i in range(len(A)):
    if A[i]!=B[i]:
        print i

Upvotes: 1

Joe
Joe

Reputation: 47619

>>> [index for (_, index) in set(zip(A, xrange(len(A)))) - set(zip(B, xrange(len(B))))]
[5, 7]

What on earth is this doing?

  1. Zip the list with incrementing numbers. So, produce a list of tuples where the first value is the element in the list, and the second is its index.
  2. Create sets of out each, so they can be compared with set functions. Tuples are immutable, therefore hashable, therefore can be stored in a set
  3. Take the set difference between the two
  4. Pick out the index of the different items

EDIT

Thanks to Roman's comment, this is simpler, but does the same thing.

>>> [index for (index, _) in set(enumerate(A)) - set(enumerate(B))]
[5, 7]

Note that while zip produces a list, enumerate produces an enumerable, which is immediately enumerated to build the list. Also it produces tupes of type (index, value) rather than (value, index) as in the above answer.

Upvotes: 4

Related Questions