jaycodez
jaycodez

Reputation: 1919

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?

Upvotes: 115

Views: 379889

Answers (5)

shang
shang

Reputation: 24802

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

Upvotes: 82

JJ K.
JJ K.

Reputation: 91

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

Upvotes: 9

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798566

With a list comprehension:

a = [x - 13 for x in a]

Upvotes: 202

sputnikus
sputnikus

Reputation: 583

You can use map() function:

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

Upvotes: 12

Oscar Mederos
Oscar Mederos

Reputation: 29813

This will work:

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

Upvotes: 2

Related Questions