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

PythonListSum

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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]

Solution 2 - Python

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

Solution 3 - Python

You can also use map:

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

It gives:

[2, 2, 2, 2, 2]

Solution 4 - Python

try this. (I modified the example on the purpose of making it non trivial)

import operator
import numpy as np

n=10
a = list(range(n))
a1 = [1]*len(a)
an = np.array(a)

operator.add is almost more than two times faster

%timeit map(operator.add, a, a1)

than adding with numpy

%timeit an+1

Solution 5 - Python

If you don't want list comprehensions:

a = [1,1,1,1,1]
b = []
for i in a:
    b.append(i+1)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLeon palafoxView Question on Stackoverflow
Solution 1 - PythonjoaquinView Answer on Stackoverflow
Solution 2 - PythondtingView Answer on Stackoverflow
Solution 3 - PythonEnrique Pérez HerreroView Answer on Stackoverflow
Solution 4 - PythonNikolai ZaitsevView Answer on Stackoverflow
Solution 5 - PythonThe Communist DuckView Answer on Stackoverflow