Python Program to Find Difference of Two Lists
[item for item in list1 if item not in list2] or by using set difference with list(set(list1) - set(list2)).Examples
How to Think About It
Algorithm
Code
list1 = [1, 2, 3, 4] list2 = [2, 4] difference = [item for item in list1 if item not in list2] print(difference)
Dry Run
Let's trace the example where list1 = [1, 2, 3, 4] and list2 = [2, 4] through the code.
Start with list1 and list2
list1 = [1, 2, 3, 4], list2 = [2, 4]
Check each item in list1 if it is not in list2
1 not in [2, 4] is True, 2 not in [2, 4] is False, 3 not in [2, 4] is True, 4 not in [2, 4] is False
Collect items that are True
Keep 1 and 3
Resulting difference list
[1, 3]
| Item in list1 | Is item not in list2? | Keep item? |
|---|---|---|
| 1 | True | Yes |
| 2 | False | No |
| 3 | True | Yes |
| 4 | False | No |
Why This Works
Step 1: Check membership with <code>not in</code>
The code uses item not in list2 to test if each item from the first list is missing in the second list.
Step 2: Use list comprehension to filter
List comprehension creates a new list by including only items that pass the membership test, making the code concise and readable.
Step 3: Return the filtered list
The resulting list contains only those elements unique to the first list, effectively the difference.
Alternative Approaches
list1 = [1, 2, 3, 4] list2 = [2, 4] difference = list(set(list1) - set(list2)) print(difference)
list1 = [1, 2, 3, 4] list2 = [2, 4] difference = list(filter(lambda x: x not in list2, list1)) print(difference)
Complexity: O(n*m) time, O(n) space
Time Complexity
The list comprehension checks each item in list1 against all items in list2, leading to O(n*m) time where n and m are the lengths of the lists.
Space Complexity
A new list is created to store the difference, so space complexity is O(n) in the worst case when all items are unique.
Which Approach is Fastest?
Using set difference reduces time to O(n + m) but loses order and duplicates; list comprehension keeps order but is slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| List Comprehension | O(n*m) | O(n) | Preserving order and duplicates |
| Set Difference | O(n + m) | O(n + m) | Large lists where order doesn't matter |
| Filter with Lambda | O(n*m) | O(n) | Functional style preference |
not in checks membership and try to use subtraction directly on lists, which causes errors.