Finding the difference between two lists in Python can be done using list comprehension or the set()
function. Here are two examples:
Example 1:
Python
x
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
difference = [item for item in list1 if item not in list2]
print(f"The difference between list1 and list2 is: {difference}")
Output:
The difference between list1 and list2 is: [1, 2]
Example 2:
Python
fruits1 = ['apple', 'banana', 'orange']
fruits2 = ['orange', 'kiwi', 'melon']
difference = list(set(fruits1) - set(fruits2))
print(f"The difference between fruits1 and fruits2 is: {difference}")
Output:
The difference between fruits1 and fruits2 is: [‘banana’, ‘apple’]