/  Technology   /  Get difference between two lists in Python
Get difference between two lists in Python

Get difference between two lists in Python

 

The difference between two lists results in a list containing the items that are in the first list but not the second.

For example:

The difference between lists [1, 3, 5] and [5, 7, 9] gives list [1, 2]. 

 

Whereas, symmetric difference between two lists results in a list containing elements from any one of the lists but are not in both of them. 

For example:

The symmetric difference between [1, 3, 5] and [5, 7, 9] is [1, 3, 7, 9].

 

Now let’s learn how to find these differences.

 

1. Using in and not in operators:

The in operator checks if a value is present in a given sequence or not and returns a Boolean value, True if present else False. The not in operator works exactly in the converse way.

Example:

list_1 = [1, 3, 5]
list_2 = [5, 7, 9]

list_difference = []

for ele in list_1:
   if ele not in list_2:
      list_difference.append(ele)

print(list_difference)

Output:

 

2. Using list comprehension with ‘in’ and ‘not in’:

This is a one-liner alternative to the above method.

Example:

list_1 = [1, 3, 5]
list_2 = [5, 7, 9]

list_difference = [ele for ele in list_1 if ele not in list_2]

print(list_difference)

Output:

 

3. Using set():

A set is a data structure that is both unordered and unindexed. They store collections of unique items separated by commas enclosed within parentheses. Sets won’t store duplicate values, unlike lists.

 

As we know, sets cannot store duplicate items, we explicitly convert the lists into sets and get the difference using the subtract operator. Now we convert this difference into list type using the list() function.

Example:

list_1 = [1, 3, 5]
list_2 = [5, 7, 9]

set_difference = set(list_1) - set(list_2)
list_difference = list(set_difference)

print(list_difference)

Output:

 

4. Using symmetric_difference():

We first convert both lists into sets using the set() function. We then find the symmetric difference by set_1.symmetric_difference(set_2). Once we get the symmetric difference we convert it into list type using the list() function.

Example:

list_1 = [1, 3, 5]
list_2 = [5, 7, 9]

difference = set(list_1).symmetric_difference(set(list_2))
list_difference = list(difference)

print(list_difference)

Output:

 

Leave a comment