Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you add integers to a list in Python?

There are four methods to add elements to a List in Python. append(): append the object to the end of the list. insert(): inserts the object before the given index. extend(): extends the list by appending elements from the iterable.

Can we add integer in list?

Yes, it is possible since lists are mutable.


new_list = [x+1 for x in my_list]

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]

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

list-comprehensions python.


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)

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]