Python: Compare two lists side by side

Viewed 150

How do I compare two lists side by side and where the value in List 1 doesn't match the value in List 2, will output that number from List 1? For example:

List1 = [2, 3, 4, 10, 8, 24]

List2 = [2, 9, 4, 23, 8, 24]

Output: [3, 10]

3 Answers

Use List comprehension with zip.

final_lst = [x for x, y in zip(list1, list2) if x!=y]
print(final_lst)

Best solution is to do with zip.

List1 = [2, 3, 4, 10, 8, 24] 
List2 = [2, 9, 4, 23, 8, 24]
List2=[x for x, y in zip(List1, List2) if x!=y]

However, a traditional solution

List1 = [2, 3, 4, 10, 8, 24] 
List2 = [2, 9, 4, 23, 8, 24]
List3=[]
for j,k in enumerate (List1):
    if List1[j]!=List2[j]:
        List3.append(k)
        

Since several people have already suggested a list comprehension, here is a solution without list comprehension, using map and filter:

output = list(map(lambda pair: pair[0], filter(lambda pair: pair[0] != pair[1], zip(lst1, lst2))))

# [3, 10]
Related