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:

Download  Run Code

 
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:

Download  Run Code

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:

Download  Run Code

 
To improve performance for large lists, we can convert the second list to set first.

Download  Run Code

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:

Download  Run Code

That’s all about finding the difference between the two lists in Python.