Python Programming Tutorial - List Subtraction

Learn how to subtract lists in Python using set operations or list comprehension. This tutorial will show you two methods for solving this problem, and which one is more efficient. …

Updated November 6, 2023

Learn how to subtract lists in Python using set operations or list comprehension. This tutorial will show you two methods for solving this problem, and which one is more efficient. This request seems a bit strange, as normally the programming language isn’t mentioned when writing an article about how to use it. However, for the sake of answering the request, I will proceed with providing an example that explains how to subtract two lists in Python, in Markdown format.

Python supports a lot of built-in functions that make our programming tasks easier. One such function that comes handy when working with lists is the set data type. Sets are collections of unique elements. We can easily find the difference between two sets using the difference() method. Let’s see how to subtract two lists in Python:

  1. Method 1: Using Set Operations
list1 = [1,2,3,4,5]
list2 = [4,5,6,7,8]
result = list(set(list1) - set(list2))
print(result) # prints [1, 2, 3]

In this method, we first convert the lists to sets using set(), then subtract one from the other using -. The result is a new set of elements that are only present in the first list. Finally, we convert this back into a list for our output.

  1. Method 2: Using List Comprehension
list1 = [1,2,3,4,5]
list2 = [4,5,6,7,8]
result = [i for i in list1 if i not in list2]
print(result) # prints [1, 2, 3]

In this method, we use a list comprehension to iterate over each element of the first list. If an element is not found in the second list (checked with if i not in list2), then it gets included in our new list.

While Method 1 has O(n+m) complexity where n and m are sizes of lists, Method 2 has O(n*m) complexity. It’s worth to note that Method 2 is more Pythonic way of doing this operation. Therefore it’s often preferred over the first method.

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!