Rhys
Rhys

Reputation: 5282

Python - Compare two lists in a comprehension

I'm trying to understand how comprehensions work.

I would like to loop through two lists, and compare each to find differences. If one/or-more word(s) is different, I would like to print this word(s).

I'd like this all in one nice line of code, which is why I'm interested in comprehensions.

Upvotes: 7

Views: 27036

Answers (3)

Lennart Regebro
Lennart Regebro

Reputation: 172319

Doing it in "one nice line of code" is code golf, and misguided. Make it readable instead.

for a, b in zip(list1, list2):
    if a != b:
       print(a, "is different from", b) 

This is not different in any significant way from this:

[print(a, "is different from", b) for a, b in zip(list1, list2) if a!=b]

Except that the expanded version easier to read and understand than the comprehension.

Upvotes: 21

dting
dting

Reputation: 39287

If you want to compare two lists for differences, I think you want to use a set.

s.symmetric_difference(t)   s ^ t   new set with elements in either s or t but not both

example:

>>> L1 = ['a', 'b', 'c', 'd']
>>> L2 = ['b', 'c', 'd', 'e'] 
>>> S1 = set(L1)
>>> S2 = set(L2)
>>> difference = list(S1.symmetric_difference(S2))
>>> print difference
['a', 'e']
>>> 

one-line form?

>>> print list(set(L1).symmetric_difference(set(L2)))
['a', 'e']
>>> 

if you really want to use a list comprehension:

>>> [word for word in L1 if word not in L2] + [word for word in L2 if word not in L1]
['a', 'e']

much less efficient as the size of the lists grow.

Upvotes: 5

überjesus
überjesus

Reputation: 834

Like kriegar suggested using sets is probably the easiest solution. If you absolutely need to use list comprehension, I'd use something like this:

list_1 = [1, 2, 3, 4, 5, 6]
list_2 = [1, 2, 3, 0, 5, 6]

# Print all items from list_1 that are not in list_2 ()
print(*[item for item in list_1 if item not in list_2], sep='\n')

# Print all items from list_1 that differ from the item at the same index in list_2
print(*[x for x, y in zip(list_1, list_2) if x != y], sep='\n')

# Print all items from list_2 that differ from the item at the same index in list_1
print(*[y for x, y in zip(list_1, list_2) if x != y], sep='\n')

Upvotes: 16

Related Questions