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?

29th Nov 2023, 3:07 PM
Ketan Lalcheta
8 Respostas
+ 11
# in your code x is the element ā not the index for idx in range(len(a)): a[idx] = a[idx] + 2
29th Nov 2023, 3:13 PM
Lisa
+ 9
# Another Pythonic way is using "enumerate" li = [1, 2, 3] for idx, el in enumerate(li): li[idx] = el + 2 print(li)
29th Nov 2023, 3:22 PM
Lisa
+ 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
29th Nov 2023, 3:48 PM
Denise RoĆberg
+ 7
just as a note: list(map(...)) would create a new list.
29th Nov 2023, 3:50 PM
Lisa
+ 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])
29th Nov 2023, 4:02 PM
Angelo Abi Hanna
+ 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/
29th Nov 2023, 4:27 PM
Denise RoĆberg
+ 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. š¤
29th Nov 2023, 3:39 PM
Lisa
+ 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 ?
29th Nov 2023, 3:18 PM
Ketan Lalcheta