How to Subtract Two Python Lists (Element-Wise)?

4.9/5 - (9 votes)

Problem Formulation and Solution Overview

This article will show you how to subtract two Lists in Python.

💡 Note: Before subtracting these Lists, ensure each List is of the same length and contains subtractable data. For example, subtracting a List of strings from a List of integers or floats will result in an error. Whereas subtracting a List of integers from a List of floats, or vice-versa will work.

This article uses two (2) Lists, one List containing 5 integer values and the other 5 float values.

For example:

  • Input 1: [1, 2, 3, 4, 5]
  • Input 2: [1, 2, 3, 4, 1]
  • Output: [0, 0, 0, 0, 4]

💬 Question: How would we write code to subtract two lists?

We can accomplish this task by one of the following options:


Method 1: Use List Comprehension and zip()

This example uses List Comprehension and the zip() function to subtract two (2) Lists.

list_ints   = [2028, 3913, 2816, 4301, 1853]
list_floats = [335.36, 442.88, 200.54, 327.11, 410.09]

new_list = [round(x-y,2) for x, y in zip(list_ints, list_floats)]
print(new_list)

The above code declares two (2) Lists: a List of integers and a List of floats. These save to the variables list_ints and list_floats, respectively.

The next line uses List Comprehension which does the following:

  • The zip() function is called and passed two (2) arguments: iterables. In this case, list_ints and list_floats. This function returns a zip object iterator (for example: <zip object at 0x000001ED24253B80>).
  • Next, each element from list_ints (x) is subtracted from int_floats (y) via the zip object shown above
  • The results from this operation are rounded down to two (2) decimal places.

These results save to new_list and output to the terminal.

[1692.64, 3470.12, 2615.46, 3973.89, 1442.91]

💡Note: To ensure the results have only two (2) decimal places, the round() function was used.

A Simple Introduction to List Comprehension in Python

Method 2: Use np.subtract()

This example uses the np.subtract() function from the NumPy library to subtract two (2) Lists.

The NumPy library will need to be installed to run this code error-free. Click here if you require installation instructions.

import numpy as np

list_ints = np.array([2028, 3913, 2816, 4301, 1853])
list_floats = np.array([335.36, 442.88, 200.54, 327.11, 410.09])
new_list = np.subtract(list_ints, list_floats)
print(new_list)

The first line of the above code imports the NumPy library to make the np_array() and np.subtract() functions available.

The following two (2) lines create two (2) Lists, a List of integers and a List of floats. These Lists are converted to a NumPy array() and saved to the variables list_ints and list_floats, respectively.

If output to the terminal, the contents of these Lists appear as follows:

[335.36 442.88 200.54 327.11 410.09]
[1692.64 3470.12 2615.46 3973.89 1442.91]

Next, the np.subtract() function is called and passed two (2) NumPy arrays. In this case, list_ints and list_floats.

The subtraction operation is performed (np.subtract(list_ints, list_floats)) on said Lists, and the results save to new_list and are output to the terminal.

[1692.64 3470.12 2615.46 3973.89 1442.91]
NumPy Tutorial - Everything You Need to Know to Get Started

Method 3: Use operator.sub and map()

This example imports the operator.sub in conjunction with the map() function to subtract two (2) Lists.

import operator

list_ints   = [2028, 3913, 2816, 4301, 1853]
list_floats = [335.36, 442.88, 200.54, 327.11, 410.09]
print(list(map(operator.sub, list_ints, list_floats)))

The first line in the above code imports the operator library. This library offers alternate ways to perform standard Python operations, such as add, subtract, multiply and much, much more!

The following two (2) lines create two (2) Lists, a List of integers and a List of floats. These Lists are saved to the variables list_ints and list_floats, respectively.

The next line calls the print() function.

Inside print(), the map() function is called and passed three (3) arguments: the operation to perform (operator.sub), an iterable (list_ints), and another iterable (list_floats) which return a map object.

If the map object was output to the terminal, an object similar to below would display.

<map object at 0x0000024DEEB3B190>

The subtraction operator is then performed, and the results convert to a List and output to the terminal.

[1692.6399999999999, 3470.12, 2615.46, 3973.89, 1442.91]
Mastering the Python Map Function [+Video]

Method 4: Use map() and a lambda

This example uses a lambda in conjunction with the map() function to subtract two (2) Lists.

list_ints   = [2028, 3913, 2816, 4301, 1853]
list_floats = [335.36, 442.88, 200.54, 327.11, 410.09]
new_list = list(map(lambda x, y: x-y, list_ints, list_floats))
print(new_list)

The above code declares two (2) Lists: a List of integers and a List of floats. These save to the variables list_ints and list_floats, respectively.

The following calls the map() function. This function is passed three (3) arguments, a lambda, an iterable (list_ints), and another iterable (list_floats). The results return an iterable map object.

The next line calls the print() function.

Inside print(), the map() function is called and passed three (3) arguments: the operation to perform (operator.sub), an iterable (list_ints), and another iterable (list_floats) which return a map object.

If the map object was output to the terminal, an object similar to below would display.

<map object at 0x000001CD6480BFD0>

The subtraction operator is then performed, converted to a List, saved to new_lists and output to the terminal.

[1692.6399999999999, 3470.12, 2615.46, 3973.89, 1442.91]
Let's Play Finxter - The Lambda Function in Python

Method 5: Use List Comprehension and enumerate()

This example uses List Comprehension and enumerate() function to subtract two (2) Lists.

list_ints   = [2028, 3913, 2816, 4301, 1853]
list_floats = [335.36, 442.88, 200.54, 327.11, 410.09]
new_list = [x - list_floats[i] for i, x in enumerate(list_ints)]
print(new_list)

The above code declares two (2) Lists: a List of integers and a List of floats. These save to the variables list_ints and list_floats, respectively.

The following line uses List Comprehension to subtract two (2) Lists. This operator uses the enumerate() function and is passed one (1) argument: list_ints. The results save to new_list and are output to the terminal.

💡 Note: The enumerate() function takes, for example, a List, a Tuple, etc., as an argument. This will then add a counter and use this as a key for the said object.

Python enumerate() — A Simple Guide

Method 6: Use For Loop

This example uses a for loop to subtract two (2) Lists.

list_ints   = [2028, 3913, 2816, 4301, 1853]
list_floats = [335.36, 442.88, 200.54, 327.11, 410.09]
new_list = []

for i in range(len(list_ints)):
    new_list.append(list_ints[i] - list_floats[i])
print(new_list)

The above code declares three (2) Lists: a List of integers, a List of floats, and an empty list. These save to the variables list_ints, list_floats, and new_list, respectively.

Next a for loop is instantiated. This loop loops through each element of list_ints, perform the subtraction operation and append the results to new_list. The results are output to the terminal.

[1692.6399999999999, 3470.12, 2615.46, 3973.89, 1442.91]

Summary

This article has provided five (5) ways to subtract two Lists to select the best fit for your coding requirements.

Good Luck & Happy Coding!


Programmer Humor – Blockchain

“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.” source xkcd