To subtract a value from every number in a list:
-operator to subtract a value from every number.
a_list = [5, 15, 25, 35, 45] a_list = [item - 5 for item in a_list] print(a_list) # 👉️ [0, 10, 20, 30, 40]
We used a
list comprehension to
iterate over the list and subtracted
5 from each number.
On each iteration, we subtract
5 from the current list item and return the
Alternatively, you can use a simple
This is a four-step process:
forloop to iterate over the original list.
a_list = [5, 15, 25, 35, 45] new_list =  for item in a_list: new_list.append(item - 5) print(new_list) # 👉️ [0, 10, 20, 30, 40]
forloop works in a very similar way to the list comprehension, but instead of returning the list items directly, we append them to a new list.
The list.append() method adds an item to the end of the list.
If you use the
numpy module, you can also subtract the number directly from a
import numpy as np arr = np.array([5, 15, 25, 35, 45]) arr = arr - 5 print(arr) # 👉️ [ 0 10 20 30 40] a_list = arr.tolist() print(a_list) # 👉️ [0, 10, 20, 30, 40]
Make sure you have NumPy installed to be able to run the code sample.
pip install numpy # 👇️ or with pip3 pip3 install numpy
Subtracting a number from a
numpy array effectively subtracts the number from
each element in the array.
Note that this only works with
numpy arrays, you'd get a
TypeError if you
try to subtract a number from a native Python list.
method converts a
numpy array to a list.
Alternatively, you can use the
This is a three-step process:
list()class to convert the map object to a list.
a_list = [5, 15, 25, 35, 45] new_list = list(map(lambda item: item - 5, a_list)) print(new_list) # 👉️ [0, 10, 20, 30, 40]
The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.
mapgets called with each item in the list, subtracts
5from the item and returns the result.
The last step is to use the
list() class to convert the
map object to a
Which approach you pick is a matter of personal preference. I'd use a list comprehension because I find them quite direct and easy to read.
You can also use the
enumerate() function to subtract a value from every
number in a list.
a_list = [5, 15, 25, 35, 45] for index, item in enumerate(a_list): a_list[index] = item - 5 # 👇️ [0, 10, 20, 30, 40] print(a_list)
The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the corresponding item.
my_list = ['bobby', 'hadz', 'com'] for index, item in enumerate(my_list): print(index, item) # 👉️ 0 bobby, 1 hadz, 2 com
On each iteration, we use the
index to assign to the current list item,
5 from its value.
I've also written an article on how to sum all values in a dictionary or list of dictionaries.
You can learn more about the related topics by checking out the following tutorials: