Subtract a value from every number in a list in Python?

I have a list

 a = [49, 51, 53, 56]

How do I subtract 13 from each integer value in the list?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

With a list comprehension:

a = [x - 13 for x in a]

Solution 2

If are you working with numbers a lot, you might want to take a look at NumPy. It lets you perform all kinds of operation directly on numerical arrays. For example:

>>> import numpy
>>> array = numpy.array([49, 51, 53, 56])
>>> array - 13
array([36, 38, 40, 43])

Solution 3

You can use map() function:

a = list(map(lambda x: x - 13, a))

Solution 4

To clarify an already posted solution due to questions in the comments

import numpy

array = numpy.array([49, 51, 53, 56])
array = array - 13

will output:

array([36, 38, 40, 43])

Solution 5

This will work:

for i in range(len(a)):
  a[i] -= 13

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply