Subtract Two Lists in Python

  • Post category:List

Subtracting one list from another in Python can be done using list comprehension or the filter() function. Here are two examples:

Example 1:

list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
subtraction = [item for item in list1 if item not in list2]
print(f"The subtraction of list2 from list1 is: {subtraction}")

Output:

The subtraction of list2 from list1 is: [1, 2]

Example 2:

fruits1 = ['apple', 'banana', 'orange']
fruits2 = ['orange', 'kiwi', 'melon']
subtraction = list(filter(lambda x: x not in fruits2, fruits1))
print(f"The subtraction of fruits2 from fruits1 is: {subtraction}")

Output:

The subtraction of fruits2 from fruits1 is: [‘apple’, ‘banana’]