191

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.

Dennis
  • 14,264
  • 2
  • 48
  • 57

12 Answers12

232
new_list = [x+1 for x in my_list]
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • 8
    This talk explains it: Facts and Myths about Python Names and Values: http://nedbatchelder.com/text/names1.html – Ned Batchelder Dec 02 '16 at 13:36
  • 3
    @DaniSpringer Because you are not assigning to a list. It's the same as doing `lst = [1, 2, 3]; e = lst[0]; e += 1`. `e` doesn't have any information about where it came from, it's just a variable to which an element of a list have been assigned. After assigning something else to it, the list `lst` won't change. – Błażej Michalik Jan 12 '17 at 12:43
  • and the correspondent lazy computed one: `new_list = (x+1 for x in my_list)` – Eduardo Pignatelli Sep 14 '18 at 13:27
  • `for i,j in enumerate(list1): list1[i] += 1` works. I'm sure Eduardo's lazy generator is fastest (use `next(list1)` to print) – alchemy Jan 11 '19 at 03:37
  • thanks. but what if i have tuples in my list like: [(2, 2), (4, 8), (7, 3)]. i want to add all values in the tuples. – cagri Jan 18 '19 at 06:50
34

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]
Andrew Cox
  • 10,672
  • 3
  • 33
  • 38
  • 8
    `map(1 .__add__, ...)` works too. Note that you need a space between `1` and `.` to prevent the parser thinking it is a float – John La Rooy Feb 16 '12 at 03:15
  • 4
    I ended up encapsulating it with a list "container" to get rid of the map object `list(map(lambda x:x+1, [1,2,3]))` – Joe Jan 17 '21 at 11:47
29
>>> mylist = [1,2,3]
>>> [x+1 for x in mylist]
[2, 3, 4]
>>>

list-comprehensions python.

RanRag
  • 48,359
  • 38
  • 114
  • 167
20

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)
sushmit
  • 4,369
  • 2
  • 35
  • 38
16

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]
Rusty Rob
  • 16,489
  • 8
  • 100
  • 116
  • 4
    This is good for changing the existing list, but it still produces a new one. Is it somehow unsafe to use a generator to avoid the unneeded list creation? I.e., `_list[:]=(i+1 for i in _list)`. – Alan May 20 '17 at 15:24
  • that still creates a new list, not possible to do it inplace without a for loop i don't think – Rusty Rob Jan 16 '20 at 20:36
  • Why do you think `_list[:]=(i+1 for i in _list)` creates a new list? – Alan Jan 16 '20 at 22:14
  • I mean, it's in place, but temporarily it will create a whole new list for the rhs. See these answers: https://stackoverflow.com/questions/4948293/python-slice-assignment-memory-usage https://stackoverflow.com/questions/11877212/python-slice-assignment-of-generator-to-list – Rusty Rob Jan 17 '20 at 01:35
  • I see what you mean. Calling the temporary sequence a list confused me. Do we actually know anything about its type? Wouldn't that be implementation specific? – Alan Jan 17 '20 at 14:51
9
>>> [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.

Kracekumar
  • 19,457
  • 10
  • 47
  • 56
8
import numpy as np

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

which gives

[2, 3, 4]
mark jay
  • 1,256
  • 14
  • 23
8

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]
satomacoto
  • 11,349
  • 2
  • 16
  • 13
3

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]
Mike
  • 1,080
  • 1
  • 9
  • 25
2
list = [1,2,3,4,5]

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

print(list)
AlexStox
  • 61
  • 9
Munchjax
  • 21
  • 2
2

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]
Rajith Thennakoon
  • 3,975
  • 2
  • 14
  • 24
Preetham
  • 577
  • 5
  • 13
0

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.

Giorgio
  • 2,137
  • 3
  • 20
  • 40
Rushikesh
  • 129
  • 1
  • 4