- Python to Find Difference Between Two Lists
- Pythonic Ways to Find the Difference Between Two Lists
- Python How to Find the Difference Between Two Lists
- Asymmetric Difference between Lists in Python
- Symmetric Difference between Lists in Python
- Conclusion
- Further Reading
- Difference between Two Lists in Python: 05 Methods (with code)
- What is Python List Difference?
- 1) Using the Membership Function
- 2) Without using the set() function
- 3) Using Numpy functions
- 4) Using symmetric_difference()
- 5) Basic method
- Conclusion
Python to Find Difference Between Two Lists
In this tutorial, we’ll discover two Pythonic ways to find the Difference Between Two Lists. One of the methods is using the Python Set. It first converts the lists into sets and then gets the unique part out of that.
Other non-set methods compare two lists element by element and collect the unique ones. We can implement these by using nested for loops and with the list comprehension.
By the way, if you are not aware of the sets in Python, then follow the below tutorial. It would quickly introduce you to how Python implements the mathematical form of Set.
Pythonic Ways to Find the Difference Between Two Lists
Python Set seems to be the most obvious choice to identify the common as well as the difference of two lists. So, we are going to explore it first and then will use nested loops and list comprehension.
# Test Input list_a = [11, 16, 21, 26, 31, 36, 41] list_b = [26, 41, 36]
And we want our solution to provide the following output:
# Expected Result # list_out = list_a - list_b list_out = [11, 21, 31, 16]
Let’s start to create a program to find the difference between two lists, first using sets.
In this approach, we’ll first derive two SETs (say set1 and set2) from the LISTs (say list1 and list2) by passing them to set() function. After that, we’ll perform the set difference operation. It will return those elements from list1 which don’t exist in the second.
Here is the sample Python program to get the difference of two lists.
""" Desc: Using set() to find the difference between two lists in Python """ def list_diff(list1, list2): return (list(set(list1) - set(list2))) # Test Input list1 = [11, 16, 21, 26, 31, 36, 41] list2 = [26, 41, 36] # Run Test print(list_diff(list1, list2))
After running this, you should see the following outcome:
In this method, we’ll use nested For Loop to compare each element of the first list with the second. And while traversing, we’ll be appending every non-matching item to a new (and empty) list.
The new list would finally include the difference between the two given sequences. Below is the sample program to demonstrate this approach.
""" Desc: Nested loop to find the difference between two lists in Python """ def list_diff(list1, list2): out = [] for ele in list1: if not ele in list2: out.append(ele) return out # Test Input list1 = [11, 16, 21, 26, 31, 36, 41] list2 = [26, 41, 36] # Run Test print(list_diff(list1, list2))
After running the above program, you should see the following outcome:
It is almost a similar technique that we used in the previous one. Here, we replaced the nested loops with the list comprehension syntax.
Also, to learn Python from scratch to depth, do read our step by step Python tutorial .
Python How to Find the Difference Between Two Lists
To find the asymmetric difference between two lists in Python:
- Convert the lists to sets.
- Subtract the sets from one another to find the difference.
- Convert the result back to a list.
names1 = ["Alice", "Bob", "Charlie", "David"] names2 = ["Bob", "Charlie"] difference = list(set(names1) - set(names2)) print(difference)
Asymmetric Difference between Lists in Python
The asymmetric difference in set theory means that given sets A and B, return the elements that are in set A but not in set B. But do not return the elements that are in set B but not in A.
This image illustrates the idea:
The example you saw above is about the asymmetric difference between two lists in Python.
names1 = ["Alice", "Bob"] names2 = ["Bob", "Charlie"] difference = list(set(names1) - set(names2)) print(difference)
Even though you might expect [«Alice», «Charlie»] as neither name occurs in both sets. But because the asymmetric difference is about finding only the elements that are in set A but not in B, it only returns “Alice”.
To fix this problem, you need to calculate the symmetric difference between the two lists.
Symmetric Difference between Lists in Python
The symmetric difference in set theory means given sets A and B, return the elements that are in set A but not in set B and vice versa.
To get the symmetric difference between two lists in Python:
- Convert the lists to sets.
- Use the built-in symmetric_difference() function of sets to get the symmetric difference.
- Convert the result back to a list.
names1 = ["Alice", "Bob"] names2 = ["Bob", "Charlie"] difference = list(set(names1).symmetric_difference(set(names2))) print(difference)
Now both names that do not occur in both lists are in the result.
Conclusion
The Asymmetric difference between two lists in Python returns the items that list A has but list B does not. This means if list B has an item that is not found in A, it does not count.
To calculate the asymmetric difference in Python lists:
- Convert the lists to sets.
- Compute the difference by subtracting one set from the other.
- Convert the result to a list.
The symmetric difference between two lists in Python returns the items in list A that are not in list B and vice versa. To calculate the symmetric difference in Python lists:
- Convert the lists to sets.
- Compute the difference with symmetric_difference() method.
- Convert the result to a list.
Thanks for reading. Happy coding!
Further Reading
Difference between Two Lists in Python: 05 Methods (with code)
Lists are one of the most important data structures in Python programming. And one of the important operations on the list is to find the difference between two lists in python. We will learn about different methods to compare lists with examples and code.
What is Python List Difference?
Finding things that are present in one list but absent from the other is known as Python list difference. But remember that the comparison ordering matters. We also need to keep in mind whether we want repetition in the list or not, because the list can have duplicate values.
Before moving forward, let’s understand two types of differences:
- Asymmetric difference: It returns the items that list1 has but list2 does not. This means if list2 has an item that is not found in list1, it does not count.
- Symmetric difference: It returns the items in list1 that are not in list2 and vice versa.
Let’s now look at a few approaches to find differences between the two lists:
1) Using the Membership Function
In python, as we know we have membership operators ‘in’ and ‘not in’, We can use these operators to differentiate between the elements of a list by passing each list in for loop and implementing an if-else condition on it.
It returns an asymmetric difference between the list that is if given two lists: list1 and list2; your function will return the elements that are in list1 but not in list2. But do not return the elements that are in list2 but not in list1 for that you need to reverse the function and find the output.
You can also use the set() function to remove duplicates from a list and then iterate it using a membership operator.
# Intializing the lists List1 = [4,28,6,99,100,25,18,10,40,73] list2 = [25, 40,73,4,80,63,99,6] new_list1 = [] #empty list for i in List1: if i not in list2: new_list1.append(i) print("elements of list 1 that are not present in list 2 ",new_list1) new_list2 = [] #empty list for i in list2: if i not in List1: new_list2.append(i) print("elements of list 2 that are not present in list 1 ",new_list2)
elements of list 1 that are not present in list 2 [28, 100, 18, 10] elements of list 2 that are not present in list 1 [80, 63]
We can also cut down our coding lines and make our program easier by using list comprehension instead of loops.
You can more clearly understand what’s happening in the above code with the following image:
Here is the new code with list comprehension:
# Intializing the lists list1 = [4,28,6,99,100,25,18,10,40,73] list2 = [25, 40,73,4,80,63,99,6] s = set(list2) # set() function to remove duplicacy new_list1 = [x for x in list1 if x not in s] # List comprehension print("elements of list 1 that are not present in list 2 ",new_list1) s2=set(list1) new_list2 = [x for x in list2 if x not in s2] print("elements of list 2 that are not present in list 1 ",new_list2)
elements of list 1 that are not present in list 2 [28, 100, 18, 10] elements of list 2 that are not present in list 1 [80, 63]
2) Without using the set() function
In this approach, we don’t use any pre-built function like set(). We simply concatenate a given two lists and iterate a loop over it to check its element’s presence in both lists individually and all common elements are removed.
Hence, storing all distinct elements of both lists in a new one. It is a symmetric difference approach to the solution.
# Python code to get difference of two lists # Not using set() def Diff(list1, list2): li_dif = [i for i in list1 + list2 if i not in list1 or i not in list2] return li_dif # Driver Code list1 = [4,28,6,99,100,25,18,10,40,73] list2 = [25, 40,73,4,80,63,99,6] list3 = Diff(list1, list2) print("All different elements of two given list",list3)
All different elements of two given list [28, 100, 18, 10, 80, 63]
3) Using Numpy functions
NumPy is an open-source Python library that’s used in almost every field of science and engineering. It is used for working with multidimensional and single-dimensional array elements. It also has functions for working in the domain of linear algebra, Fourier transform, and matrices. The array object in NumPy is called ndarray.
We have so many in-built functions and out of these all functions we have concatenate(arr1,arr2) which merges two lists, and setdiff1d(arr1,arr2,assume_unique=False) which helps us to differentiate between the list i.e. It returns the ndarray which stores the unique values of arr1 which are not in arr2.
import numpy as np list1 = [4,28,6,99,100,25,18,10,40,73] list2 = [25, 40,73,4,80,63,99,6] dif_1_2 = np.setdiff1d(list1, list2) dif_2_1 = np.setdiff1d(list2, list1) new_list = [np.concatenate((dif_1_2, dif_2_1))] print("All different elements of two given list",new_list)
All different elements of two given list [array([ 10, 18, 28, 100, 63, 80])]
4) Using symmetric_difference()
The elements that are either in the first set or the second set are returned using the symmetric_difference() technique. Unlike the shared items of the two sets, the intersection is not returned by this technique.
list1 = [4,28,6,99,100,25,18,10,40,73] list2 = [25, 40,73,4,80,63,99,6] set_dif = [set(list1).symmetric_difference(set(list2))] print(set_dif)
5) Basic method
In this approach, we find the set of each list and differentiate it from another set. This is the easiest method as it does not require any pre-built function use. First, we convert the list into a set. Second, we will subtract the sets from one another to find the difference. Last, we convert the result back to a list.
list1 = [4,28,6,99,100,25,18,10,40,73] list2 = [25, 40,73,4,80,63,99,6] new_list1=set(list1)-set(list2) new_list2=set(list2)-set(list1) print("set of elements of list 1 that are not present in list 2 ",new_list1) print("set of elements of list 2 that are not present in list 1 ",new_list2)
set of elements of list 1 that are not present in list 2 10, 18, 100, 28> set of elements of list 2 that are not present in list 1 80, 63>
Conclusion
Today, we learned how to find the difference between two lists in python. If you still have any queries, we can connect you with our expert for python assignment help online anytime. Happy learning 🙂