Python - Compare two lists in a comprehension Python - Compare two lists in a comprehension python-3.x python-3.x

Python - Compare two lists in a comprehension


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.


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_2print(*[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_1print(*[y for x, y in zip(list_1, list_2) if x != y], sep='\n')


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.