For the following question, the function
• should mutate the original list
• should NOT create any new lists
• should NOT return anything
Functions that do not create new lists are said to be ”in place.” Such functions are often desirable because they do not require extra memory to operate.
Implement the function map_mut, which applies a function fn onto every element of a list called lst.
def map_mut(fn, lst):
"""Maps fn onto lst by mutation.
>>> lst = [1, 2, 3, 4]
>>> map_mut(lambda x: x**2, lst)
>>> lst
[1, 4, 9, 16]
"""
*** Your code here***
Below is the solution:
def map_mut(fn, lst):
"""Maps fn onto lst by mutation.
>>> lst = [1, 2, 3, 4]
>>> map_mut(lambda x: x**2, lst)
>>> lst
[1, 4, 9, 16]
"""
def mutate(index):
if len(lst) == index:
return
else:
lst[index] = fn(lst[index])
return mutate(index + 1)
return mutate(0)
lst = [1, 2, 3, 4]
map_mut(lambda x: x**2, lst)
Can we improve this solution in recursive approach?