0
How to modify list in python
a = [1,2,3,4,5] print(a) for x in a: x += 2 print(a) How can I get all elements of a modified by 2 in this approach?
8 Answers
+ 11
# in your code x is the element â not the index
for idx in range(len(a)):
a[idx] = a[idx] + 2
+ 9
# Another Pythonic way is using "enumerate"
li = [1, 2, 3]
for idx, el in enumerate(li):
li[idx] = el + 2
print(li)
+ 8
another way is to use map() and lambda function:
a = [1,2,3,4,5]
a = list(map(lambda x: x+2,a))
If you are not familiar with lambda functions:
def add_two(n):
return n+2
a = [1,2,3,4,5]
a = list(map(add_two,a))
https://www.programiz.com/JUMP_LINK__&&__python__&&__JUMP_LINK-programming/methods/built-in/map
+ 7
just as a note:
list(map(...)) would create a new list.
+ 3
Lisa
slightly different syntax based on preference
alternatively, one could also:
a = [1,2,3,4,5]
a = [i+2 for i in a]
print(a)
#or just
print([i+2 for i in a])
+ 3
There exists also a numpy solution.
import numpy as np
a = [1,2,3,4,5]
a = list(np.array(a)+2)
#or leave it as an numpy array:
a = np.array(a) + 2
https://www.freecodecamp.org/news/the-ultimate-guide-to-the-numpy-scientific-computing-library-for-JUMP_LINK__&&__python__&&__JUMP_LINK/
+ 2
Angelo Abi Hanna
How is that different from the previous suggestions?
Another way could be using list comprehension â but that actually creates a new list instead of modifying the existing one. đ€
+ 1
Yeah this approach is there.
I come from a c++ background where reference is there for an element
So curious whether range based for loop and accessing element using index is the only option to modify the list ?