How to add an integer to each element in a list?

PythonLoopsAddition

Python Problem Overview


If I have list=[1,2,3] and I want to add 1 to each element to get the output [2,3,4], how would I do that?

I assume I would use a for loop but not sure exactly how.

Python Solutions


Solution 1 - Python

new_list = [x+1 for x in my_list]

Solution 2 - Python

The other answers on list comprehension are probably the best bet for simple addition, but if you have a more complex function that you needed to apply to all the elements then map may be a good fit.

In your example it would be:

>>> map(lambda x:x+1, [1,2,3])
[2,3,4]

Solution 3 - Python

>>> mylist = [1,2,3]
>>> [x+1 for x in mylist]
[2, 3, 4]
>>>

list-comprehensions python.

Solution 4 - Python

if you want to use numpy there is another method as follows

import numpy as np
list1 = [1,2,3]
list1 = list(np.asarray(list1) + 1)

Solution 5 - Python

Edit: this isn't in-place

Firstly don't use the word 'list' for your variable. It shadows the keyword list.

The best way is to do it in place using splicing, note the [:] denotes a splice:

>>> _list=[1,2,3]
>>> _list[:]=[i+1 for i in _list]
>>> _list
[2, 3, 4]

Solution 6 - Python

>>> [x.__add__(1) for x in [1, 3, 5]]
3: [2, 4, 6]

My intention here is to expose if the item in the list is an integer it supports various built-in functions.

Solution 7 - Python

Python 2+:

>>> mylist = [1,2,3]
>>> map(lambda x: x + 1, mylist)
[2, 3, 4]

Python 3+:

>>> mylist = [1,2,3]
>>> list(map(lambda x: x + 1, mylist))
[2, 3, 4]

Solution 8 - Python

import numpy as np

np.add([1, 2, 3], 1).tolist()

which gives

[2, 3, 4]

Solution 9 - Python

list = [1,2,3,4,5]

for index in range(len(list)):
      list[index] = list[index] +1

print(list)

Solution 10 - Python

Came across a not so efficient, but unique way of doing it. So sharing it across.And yes it requires extra space for another list.

from operator import add
test_list1 = [4, 5, 6, 2, 10]
test_list2 = [1] * len(test_list1)

res_list = list(map(add, test_list1, test_list2))

print(test_list1)
print(test_list2)
print(res_list)

#### Output ####
[4, 5, 6, 2, 10]
[1, 1, 1, 1, 1]
[5, 6, 7, 3, 11]

Solution 11 - Python

Just in case anyone was looking for a solution that only uses built-ins and no lambdas:

from functools import partial
from operator import add


my_list = range(1, 4)  # list(my_list) #=> [1, 2, 3]
my_list_plus_one = list(map(partial(add, 1), my_list)  #=> [2, 3, 4]

Solution 12 - Python

Many of the answers above are very good. I've also seen some weird answers that will do the job. Also, the last answer seen was through a normal loop. This willingness to give answers leads me to itertools and numpy, which will do the same job in a different way.

Here I present different ways to do the job, not answered above.

import operator
import itertools

x = [3, 5, 6, 7]

integer = 89

"""
Want more vairaint can also use zip_longest from itertools instead just zip
"""
#lazy eval
a = itertools.starmap(operator.add, zip(x, [89] * len(x))) # this is not subscriptable but iterable
print(a)
for i in a:
  print(i, end = ",")


# prepared list
a = list(itertools.starmap(operator.add, zip(x, [89] * len(x)))) # this returns list
print(a)



# With numpy (before this, install numpy if not present with `pip install numpy`)
import numpy

res = numpy.ones(len(x), dtype=int) * integer + x # it returns numpy array
res = numpy.array(x) + integer # you can also use this, infact there are many ways to play around
print(res)
print(res.shape) # prints structure of array, i.e. shape

# if you specifically want a list, then use tolist

res_list = res.tolist()
print(res_list)

Output

>>> <itertools.starmap object at 0x0000028793490AF0> # output by lazy val
>>> 92,94,95,96,                                     # output of iterating above starmap object
>>> [92, 94, 95, 96]                                 # output obtained by casting to list
>>>                   __
>>> # |\ | |  | |\/| |__| \ /
>>> # | \| |__| |  | |     |
>>> [92 94 95 96]                                    # this is numpy.ndarray object
>>> (4,)                                             # shape of array
>>> [92, 94, 95, 96]                                 # this is a list object (doesn't have a shape)

My sole reason to highlight the use of numpy is that one should always do such manipulations with libraries like numpy because it is performance efficient for very large arrays.

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
Questionuser1212818View Question on Stackoverflow
Solution 1 - PythonNed BatchelderView Answer on Stackoverflow
Solution 2 - PythonAndrew CoxView Answer on Stackoverflow
Solution 3 - PythonRanRagView Answer on Stackoverflow
Solution 4 - PythonsushmitView Answer on Stackoverflow
Solution 5 - Pythonrobert kingView Answer on Stackoverflow
Solution 6 - PythonKracekumarView Answer on Stackoverflow
Solution 7 - PythonsatomacotoView Answer on Stackoverflow
Solution 8 - Pythonmark jayView Answer on Stackoverflow
Solution 9 - PythonMunchjaxView Answer on Stackoverflow
Solution 10 - PythonPreethamView Answer on Stackoverflow
Solution 11 - PythonMikeView Answer on Stackoverflow
Solution 12 - PythonRushikeshView Answer on Stackoverflow