Find difference between the two lists in Python
This post will discuss how to find the difference between the two lists in Python. The solution should return items present in the first list but not in the second list.
1. Using set() function
A simple solution is to convert both lists to set data structure and then calculate the difference between them using the - operator. The difference operator returns a set of items that are present in one set but not in another. We can then convert the result back to a list if needed. Here is an example of how to use this method:
|
1 2 3 4 5 6 7 |
first = [2, 1, 3, 4, 1] second = [3, 4, 5] # The `set()` function is used to create sets diff = list(set(first) - set(second)) print(diff) # prints [1, 2] |
Note that this method may not preserve the order or duplicates of the original lists.
2. Using difference() function
The set object also offers built-in function difference(), which returns a new set with elements in the first set that are not in the second set. Here is an example of how to use this function:
|
1 2 3 4 5 6 |
first = [2, 1, 3, 4, 1] second = [3, 4, 5] diff = list(set(first).difference(set(second))) print(diff) # prints [1, 2] |
3. Using List Comprehension
Both above solutions does not preserve the original order of elements in the input list. Also, any duplicate entries in the first list are eliminated in the output list. To preserve order and allow duplicates entries, we can use the list comprehension which allows us to create a new list from an existing one by applying some expression or condition on each element. We can use a nested list comprehension to iterate over each element of each list and append them to a new list if they satisfy some condition. Here is an example:
|
1 2 3 4 5 6 |
first = [2, 1, 3, 4, 1] second = [3, 4, 5] diff = [x for x in first if x not in second] print(diff) # prints [2, 1, 1] |
To improve performance for large lists, we can convert the second list to set first.
|
1 2 3 4 5 6 7 |
first = [2, 1, 3, 4, 1] second = [3, 4, 5] s = set(second) diff = [x for x in first if x not in s] print(diff) # prints [2, 1, 1] |
4. Finding Symmetric Difference
Finally, if we need the symmetric difference between two sets, we can convert the lists to sets and then use the symmetric_difference() function or symmetric difference operator (^). This will return a set of elements that are present in either set but not both sets. For example:
|
1 2 3 4 5 |
first = [2, 1, 3, 4, 1] second = [3, 4, 5] diff = list(set(first) ^ set(second)) print(diff) # prints [1, 2, 5] |
That’s all about finding the difference between the two lists in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)