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

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 it?

I guess I would use a for loop, but I don’t know exactly how.

+90
python loops addition
Feb 16 2018-12-12T00:
source share
9 answers
 new_list = [x+1 for x in my_list] 
+109
Feb 16 2018-12-12T00:
source share
 >>> mylist = [1,2,3] >>> [x+1 for x in mylist] [2, 3, 4] >>> 

python list .

+22
Feb 16 2018-12-12T00:
source share

Other list comprehension answers are probably the best choice for a simple add, but if you have a more complex function that you need to apply to all elements, then a map might be good.

In your example, this would be:

 >>> map(lambda x:x+1, [1,2,3]) [2,3,4] 
+15
Feb 16 2018-12-12T00:
source share

if you want to use numpy, the following method exists

 import numpy as np list1 = [1,2,3] list1 = list(np.asarray(list1) + 1) 
+11
Dec 14 '16 at 5:46
source share
 >>> [x.__add__(1) for x in [1, 3, 5]] 3: [2, 4, 6] 

My intention is to expose whether the item in the list is an integer that supports various built-in functions.

+10
Feb 16 2018-12-12T00:
source share

First, do not use the word list for your variable. It obscures the list keyword.

The best way to do this in place with splicing, note that [:] stands for splicing:

 >>> _list=[1,2,3] >>> _list[:]=[i+1 for i in _list] >>> _list [2, 3, 4] 
+5
Feb 16 '12 at 3:00
source share

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] 
+4
Feb 16 2018-12-12T00:
source share
 list = [1,2,3,4,5] for index in range(5): list[index] = list[index] +1 print(list) 
0
Dec 17 '18 at 5:10
source share

I came across a not very effective, but unique way to do this. So share it with each other. And yes, this requires extra space for another list.

 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] 
0
Apr 27 '19 at 9:21
source share



All Articles