What do you mean when you first heard subtracting two lists? Python does not have a built-in subtraction operator. You can think of it as taking elements from one list and remove from another list. That seems logical.
In Python, – (minus or negative sign) is used to subtract single numbers from one another, but it doesn’t work for data structures like lists. The minus operator isn’t defined for lists. If you try [1,2,3] – [1,2,3], it gives an error.
In this article, we will perform element-wise subtraction.
Here are the two easy ways to subtract two lists:
- Using List comprehension and zip()
- Using for loop
Method 1: Using List comprehension and zip()
You can use the combination of list comprehension and zip() function to perform element-wise subtraction of two lists. But both lists should have equal lengths. If they are not, zip truncates to the shorter one.
The zip() function combines the elements of list1 and list2 into pairs. The list comprehension iterates over these pairs and subtracts the second element of each pair from the first.
list1 = [5, 10, 15, 20] list2 = [3, 7, 9, 12] difference = [a - b for a, b in zip(list1, list2)] print("Subtraction of two lists:", difference) # Output: Subtraction of two lists: [2, 3, 6, 8]
But how do we handle cases where the lists are of unequal lengths? In that case, we can pad them with 0s to make them equal lengths.
We can pad shorten lists with zeros using itertools for unequal lengths.zip_longest() function.
import itertools list1 = [5, 10, 15, 20] list2 = [3, 7] difference = [a - b for a,b in itertools.zip_longest(list1, list2, fillvalue=0)] print("Subtraction of two lists:", difference) # Output: Subtraction of two lists: [2, 3, 15, 20]
Method 2: Using for loop
When using an iterative for-loop approach, you iterate through both lists and manually apply the subtraction. By default, this approach preserves the order of the lists.
If the elements of the second list are greater than the first list, it will return negative values.
list1 = [5, 10, 15, 20] list2 = [3, 7, 20, 40] final_list = [] for k in range(len(list1)): final_list.append(list1[k] - list2[k]) print(final_list) # Output: [2, 3, -5, -20]
If you need to subtract only when the elements of list1 are greater than those in list2, you should include a condition and add 0 for the elements where the elements of list2 are greater than those of list1.
list1 = [5, 10, 15, 20] list2 = [3, 7, 20, 40] final_list = [] for k in range(len(list1)): if list1[k] > list2[k]: final_list.append(list1[k] - list2[k]) else: final_list.append(0) print(final_list) # Output: [2, 3, 0, 0]
You can see that 5-3=2, 10-7=3, and then 0, 0 because 15 is less than 20 and 20 is less than 40. So, it appends 0 using the list.append() function in both cases based on our manual condition.