How to add an integer to each element 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 that?

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

Answers


new_list = [x+1 for x in my_list]

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

list-comprehensions 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]

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)

>>> [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.


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]

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]

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

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

print(list)

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.

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]

Need Your Help

Silent install apk programmatically by system app (without root)

android android-install-apk

I have system-level app with android:sharedUserId="android.uid.system" (UID: 1000).

How to show the reorder controls in UITableView with delete buttons

iphone uitableview ios4

I read the documentation about how to manage deletion and reordering of rows in a UITableView. I created the edit button and I'm able to delete rows. I would like the user to be able to reorder the...