Estimated reading time: 2 minutes

Often you are going to be asked to compare lists, and you need a quick way to complete.

Here we are going to take through three ways to complete this, if you have more comment below.

Looping to find common values between lists

A simple loop can help you find data that is common to two lists:

# compare for similar values list1 = ["1", "2", "3", "4"] list2 = ["1", "2", "3", "4", "5"] for i in list1: for j in list2: if i in j: print(i)

which yields:

1 2 3 4

Compare for an item in one list and not in the other

There maybe times you wish to find only the values that are in one list and not the other.

Below we use a one line piece of code using list comprehension, which does the same as a loop:

list1 = ["1", "2", "3", "4"] list2 = ["1", "2", "3", "4", "5"] for item in [x for x in list2 if x not in list1]: print(item)

which gives the result of:

5

comparing lists using the set method

The third way uses python sets, which essentially finds the intersection between two lists, like a Venn diagram.

Here we use set to find what values are not common to each list by using subtraction:

list1 = ["1", "2", "3", "4"] list2 = ["1", "2", "3", "4", "5"] a = set(list1) b = set(list2) c = b-a print(c)

which gives you:

{'5'}

Alternatively you could find what is common to both:

list1 = ["1", "2", "3", "4"] list2 = ["1", "2", "3", "4", "5"] a = set(list1) b = set(list2) c = a.intersection(b) print(c)

and your result will be:

{'1', '3', '4', '2'}

Remember that using sets will return them unordered, if you want them ordered then apply the following to the above code:

a = set(list1) b = set(list2) c = a.intersection(b) d=sorted(c) print(type(d)) print(d)

and the output will be:

<class 'list'> ['1', '2', '3', '4']

One thing to note that the sorted method above returns the set as a list not as a set.

There are plenty of resources online where you can learn about sets.