listpython-3.xlist-comprehension

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.


Solution

  • 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')