Reputation:
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.
Upvotes: 202
Views: 466218
Reputation: 154
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.
Upvotes: 0
Reputation: 1310
Just in case anyone was looking for a solution that only uses built-ins and no lambda
s:
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]
Upvotes: 3
Reputation: 21
list = [1,2,3,4,5]
for index in range(len(list)):
list[index] = list[index] +1
print(list)
Upvotes: 2
Reputation: 1284
import numpy as np
np.add([1, 2, 3], 1).tolist()
which gives
[2, 3, 4]
Upvotes: 8
Reputation: 158
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.
Upvotes: 0
Reputation: 577
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]
Upvotes: 2
Reputation: 17213
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]
Upvotes: 16
Reputation: 20419
>>> [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.
Upvotes: 10
Reputation: 4601
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)
Upvotes: 20
Reputation: 11973
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]
Upvotes: 8
Reputation: 10998
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]
Upvotes: 35