The Basics of Subtraction in Python Lists

List subtraction, also known as set difference, is a vital concept in programming. It’s a common operation that takes two lists as input and produces a new list containing only the elements from the f …

Updated November 4, 2023

List subtraction, also known as set difference, is a vital concept in programming. It’s a common operation that takes two lists as input and produces a new list containing only the elements from the first list that are not present in the second one. In this guide, we will go over how to perform this task in Python.

Python provides us with an easy way of subtracting or finding difference between two lists through the use of the - operator. We can do it as follows:

list1 = [1, 2, 3, 4, 5]
list2 = [2, 4, 6, 8]
difference_list = list(set(list1) - set(list2))
print(difference_list)

In the code above, set() function is used to remove duplicate elements from both lists and list() function is then used to convert it back into a list.

This works because sets in Python are unordered collections of unique elements. Any duplicates have been removed when we turn the first list into a set. Therefore, when we subtract the second set (which has no duplicates) from this set, all elements present in both lists have been removed. The result is the elements that are only present in list1.

However, please note that, this method will not preserve the original order of elements and also it will remove duplicate values from list1. If you need to subtract a list while preserving the original order and considering duplicates as well, then you might have to use different approach like:

def subtract_lists(list1, list2):
    return [i for i in list1 if i not in list2]

list1 = [1, 2, 3, 4, 5]
list2 = [2, 4, 6, 8]
difference_list = subtract_lists(list1, list2)
print(difference_list)

This function will keep the original order of elements and also consider duplicates. It works by using a list comprehension to iterate over list1 checking if each item is not in list2. If it’s not there, that item gets added to the new list, which we return at the end.

Hey! Do you love Python? Want to learn more about it?
Let's connect on Twitter or LinkedIn. I talk about this stuff all the time!