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
Ketan Lalcheta - avatar
8 Answers
+ 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
Lisa - avatar
+ 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
Lisa - avatar
+ 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
Denise Roßberg - avatar
+ 7
just as a note: list(map(...)) would create a new list.
29th Nov 2023, 3:50 PM
Lisa
Lisa - avatar
+ 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
Angelo Abi Hanna - avatar
+ 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
Denise Roßberg - avatar
+ 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
Lisa - avatar
+ 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
Ketan Lalcheta - avatar