Examples of how to add a number to each element of a list in python:
Add a number to a list of integers
Add +10 to each integer of a list using a "list comprehension":
>>> l2 = [i+10 for i in l]>>> l2[13, 11, 15, 18, 14]
Increment a list of integer numbers:
>>> l = [3,1,5,8,4]>>> l2 = [i+1 for i in l]>>> l2[4, 2, 6, 9, 5]
Add a number to a list of reals
Increment a list of real numbers:
>>> import numpy as np>>> l = [i for i in np.arange(0,2,0.5)]>>> l[0.0, 0.5, 1.0, 1.5]>>> [i+1 for i in l][1.0, 1.5, 2.0, 2.5]
Add a number to a list of strings
Add a number to a list of strings:
>>> s2 = [i+str(10) for i in s]>>> s2['coucou10', 'hi10', 'hello10']
Note: it is also possible to add a string to a list of strings:
>>> s = ['coucou', 'hi', 'hello']>>> s2 = [i+' aaa' for i in s]>>> s2['coucou aaa', 'hi aaa', 'hello aaa']
References
| Links | Site |
|---|---|
| How to add an integer to each element in a list? | stackoverflow |
| List Comprehensions in Python | pythonforbeginners.com |
| str() | programiz.com |
