Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 814
jaycodez Avatar asked Feb 07 '11 05:02

jaycodez


People also ask

How do you subtract a value in Python?

To subtract two numbers in Python, use the subtraction(-) operator. The subtraction operator (-) takes two operands, the first operand on the left and the second operand on the right, and returns the difference of the second operand from the first operand.

How do you subtract a number from an array in Python?

subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise. Parameters : arr1 : [array_like or scalar]1st Input array. arr2 : [array_like or scalar]2nd Input array.


2 Answers

With a list comprehension:

a = [x - 13 for x in a] 
like image 110
Ignacio Vazquez-Abrams Avatar answered Sep 29 '22 17:09

Ignacio Vazquez-Abrams


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]) 
like image 30
shang Avatar answered Sep 29 '22 17:09

shang