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

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


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

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

gives

[3, 3, 3, 3, 3]


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


You can also use map:

a = [1, 1, 1, 1, 1]b = 1list(map(lambda x: x + b, a))

It gives:

[2, 2, 2, 2, 2]