In this tutorial, you’ll learn how to subtract two lists in Python. Before performing list subtraction, keep in mind that both lists should be of the same length and all the elements should be of the same datatype.
You can also get a better understanding of lists in Python by Python List Tutorials.
For instance, suppose you have two lists and you want to perform a subtraction between these two lists i.e.,
Input list 1 = [7,6,2,4,-2,8,9] Input list 2 = [2,9,-3,0,9,5,6] Output: Result = [7,6,2,4,-2,8,9] - [2,9,-3,0,9,5,6] = [5,-3,5,4,-11,3,3]
There are different methods to perform list subtraction. Three of them are discussed in detail below.
subtract two lists using Zip() Function
In this method, we’ll pass the two input lists to the Zip Function. Then, iterate over the zip object using for loop. On every iteration, the program will take an element from list1 and list2, subtract them and append the result into another list.
# Create and initialize two lists list1 = [9,1,3,7] list2 = [4,4,5,6] #initialize a variable which will store the difference of two lists result =  for i, j in zip(list1,list2): result.append(i - j) print(result)
[5, -3, -2, 1]
perform subtraction using List Comprehension
#create and initialize two lists list1 = [9,1,3] list2 = [4,4,5] #perform subtraction and store the result in "difference" difference = [List1[i]-List2[i] for i in range(min(len(list1), len(List2)))] #print the difference of two lists print(difference)
[5, -3, -2]
difference of two lists USING numpy array
The previous two methods require traversal over the whole list. One of the simplest methods is to convert the two lists into an array. Here, np.array() function converts two lists into arrays and then uses subtract operator.
#create and initialize two lists list1 = [2,3,9,-4,7] list2 = [4,-1,5,3,8] #convert the two lists into arrays and store the difference difference = np.array(list1)-np.array(list2) #print the difference of two lists print(difference)
[-2 4 4 -7 -1]
In this article, we learned three different methods by which we can subtract two lists. If you have any queries regarding this article, contact us. Your feedback matters a lot. See more Python Tutorials