204

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.

1

13 Answers 13

247
new_list = [x+1 for x in my_list] 
Sign up to request clarification or add additional context in comments.

5 Comments

This talk explains it: Facts and Myths about Python Names and Values: nedbatchelder.com/text/names1.html
@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.
and the correspondent lazy computed one: new_list = (x+1 for x in my_list)
for i,j in enumerate(list1): list1[i] += 1 works. I'm sure Eduardo's lazy generator is fastest (use next(list1) to print)
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.
35

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] 

3 Comments

map(1 .__add__, ...) works too. Note that you need a space between 1 and . to prevent the parser thinking it is a float
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]))
map(lambda x:x+1, [1,2,3]) contains a map object not a list. Have you actually printed it?
30
>>> mylist = [1,2,3] >>> [x+1 for x in mylist] [2, 3, 4] >>> 

list-comprehensions python.

Comments

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) 

Comments

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] 

5 Comments

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).
that still creates a new list, not possible to do it inplace without a for loop i don't think
Why do you think _list[:]=(i+1 for i in _list) creates a new list?
I mean, it's in place, but temporarily it will create a whole new list for the rhs. See these answers: stackoverflow.com/questions/4948293/… stackoverflow.com/questions/11877212/…
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?
10
>>> [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.

Comments

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] 

Comments

8
import numpy as np np.add([1, 2, 3], 1).tolist() 

which gives

[2, 3, 4] 

Comments

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] 

1 Comment

Thanks a lot! This is the fastest solution according to my timeit measurements!
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] 

2 Comments

where does "add" come from?
add should import from operators, from operator import add
2
list = [1,2,3,4,5] for index in range(len(list)): list[index] = list[index] +1 print(list) 

Comments

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.

Comments

0

A lot of good solutions, here is some benchmarking.

from functools import partial from operator import add test_list = list(range(1000)); n = 3; %timeit _=list(map(lambda x:x+n, test_list)) %timeit _=[x+n for x in test_list] %timeit _=[x.__add__(n) for x in test_list] %timeit _=list(map(lambda x:x.__add__(n), test_list)) %timeit _=list(map(partial(add,n), test_list)) Out: >> 53.6 µs ± 651 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) >> 38.2 µs ± 392 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) >> 80.2 µs ± 851 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) >> 108 µs ± 513 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) >> 53.7 µs ± 332 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each) 

Seems like [x+n for x in test_list] is the fastest solution in pure python.

Comments