Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum one number to every element in a list (or array) in Python

Tags:

python

list

sum

Here I go with my basic questions again, but please bear with me.

In Matlab, is fairly simple to add a number to elements in a list:

a = [1,1,1,1,1] b = a + 1 

b then is [2,2,2,2,2]

In python this doesn't seem to work, at least on a list.

Is there a simple fast way to add up a single number to the entire list.

Thanks

like image 659
Leon palafox Avatar asked Apr 22 '11 10:04

Leon palafox


2 Answers

if you want to operate with list of numbers it is better to use NumPy arrays:

import numpy a = [1, 1, 1 ,1, 1] ar = numpy.array(a) print ar + 2 

gives

[3, 3, 3, 3, 3] 
like image 80
joaquin Avatar answered Oct 13 '22 01:10

joaquin


using List Comprehension:

>>> L = [1]*5 >>> [x+1 for x in L] [2, 2, 2, 2, 2] >>>  

which roughly translates to using a for loop:

>>> newL = [] >>> for x in L: ...     newL+=[x+1] ...  >>> newL [2, 2, 2, 2, 2] 

or using map:

>>> map(lambda x:x+1, L) [2, 2, 2, 2, 2] >>>  
like image 31
dting Avatar answered Oct 13 '22 01:10

dting