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

PythonPython 3.x

Python Problem Overview


I have a list

 a = [49, 51, 53, 56]

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

Python Solutions


Solution 1 - Python

With a list comprehension:

a = [x - 13 for x in a]

Solution 2 - Python

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 - Python

You can use map() function:

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

Solution 4 - Python

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 - Python

This will work:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjaycodezView Question on Stackoverflow
Solution 1 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 2 - PythonshangView Answer on Stackoverflow
Solution 3 - PythonsputnikusView Answer on Stackoverflow
Solution 4 - PythonJJ K.View Answer on Stackoverflow
Solution 5 - PythonOscar MederosView Answer on Stackoverflow