Get List Differences Using a List Comprehension in Python

Published by Brandon on

Let’s say we have two lists in python. How can you get the differences between the two lists? By differences, I mean get all the values that both lists don’t share. Let’s look at an example couple of lists.

l1 = [1, 3, 4, 5, 6]
l2 = [1, 2, 5, 6, 7]

Here are two lists of ints in python. There are differences between the lists, like for example, 2 is found in l2 but it isn’t in l1. Also, 3 is in l1, but not in l2.

To get the differences between the two, we are going to use list comprehensions. When we go this route, we get all the differences in their own list, in one line of code.

l1 = [1, 3, 4, 5, 6]
l2 = [1, 2, 5, 6, 7]

main_list = [x for x in l1+l2 if x not in l1 or x not in l2]

print(main_list)

Our new list, main_list, is created by a list comprehension where we add both the lists we want to compare, and only add their values if the value is not found in one list, or the other.

When we run the script above, the output is this:

[3, 4, 2, 7]

Of course, this doesn’t just have to be a list of numbers. It can also be a list of strings. Let’s try one with those too.

# Two lists of pizza toppings
l1 = ['cheese', 'green pepper', 'mushroom', 'olives']
l2 = ['cheese', 'tomatoes', 'mushroom']

main_list = [x for x in l1+l2 if x not in l1 or x not in l2]

print(main_list)

Output:

['green pepper', 'olives', 'tomatoes']

Want more content? Check out my YouTube Channel!

Categories: Python

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *