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


Question

I'm still reading the Python 3.1.3 tutorial and encountered the following problem:

How do you remove a value from a group of numbers?

# A list with a group of values
a = [49, 51, 53, 56]

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

# Attempting to minus 13 from this list - FAIL!
(a[:] = a[:] - 13)
1
68
9/30/2012 7:10:03 AM

Accepted Answer

With a list comprehension.

a[:] = [x - 13 for x in a]
117
2/7/2011 5:56:30 AM

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])

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon