Below is my sample code:-
def applyToEach(L, f):
for i in range(len(L)):
L[i] = f(L[i])
L = [1, -2, 3.333]
print('L = ', L)
print('Apply abs to each element of L.')
applyToEach(L, abs)
print('L = ', L)
Below is the O/p on the same:-
L = [1, -2, 3.333]
L = [1, 2, 3.333]
I would like to go for a map function that will modify my existing function applyToEach, so instead of using the one I used before, how can i use map function at applyToEach to get abs value of L?
CodePudding user response:
use map function:
map(abs, <your-list>)
CodePudding user response:
map
or a list comprehension will return a new object. You can't mutate existing object using those, but you can use this trick:
def applyToEach(L, f):
my_list[:] = map(f, my_list)
or
my_list[:] = [f(i) for i in my_list]
these will modify my_list
in place.
CodePudding user response:
You can try this:
def applyToEach(L, f):
L[:] = map(f, L)
L = [1, -2, 3.333]
print('L = ', L)
print('Apply abs to each element of L.')
applyToEach(L, abs)
print('L = ', L)
Output:
L = [1, -2, 3.333]
Apply abs to each element of L.
L = [1, 2, 3.333]