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

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

This question is related to python list sum

The answer is


If you don't want list comprehensions:

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

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

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

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]

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to sum

Iterating over arrays in Python 3 Get total of Pandas column Pandas: sum DataFrame rows for given columns How to find sum of several integers input by user using do/while, While statement or For statement SQL Sum Multiple rows into one Python Pandas counting and summing specific conditions SELECT query with CASE condition and SUM() Using SUMIFS with multiple AND OR conditions How to SUM parts of a column which have same text value in different column in the same row how to count the total number of lines in a text file using python