197k views
3 votes
write a function replace that consumes a list, an item old, and an item new and mutates the list by replacing old by new. if the item old is not in the list, the list should not change. you can assume that all items in the input are distinct (that is, none are the same as any others).

User Pgmank
by
8.1k points

1 Answer

5 votes

Final answer:

The function 'replace' should mutate the provided list by replacing an old item with a new one if the old item is present. It iterates over the list and makes the replacement, then ends the loop because all items are distinct.

Step-by-step explanation:

The question asks to write a function named replace that consumes three arguments: a list, an old item, and a new item. The function should mutate the list by replacing all occurrences of the old item with the new one, only if the old item exists within the list. Since the items in the list are distinct, you do not have to worry about duplicate replacements.

Here's an example of how the code for the replace function might look in Python:

def replace(lst, old, new):
for i in range(len(lst)):
if lst[i] == old:
lst[i] = new
break

In this example, the function iterates over the list using a for loop. It checks each item to see if it matches the old item. If a match is found, it replaces that item with the new item and exits the loop early since all items are distinct.

User Luisdemarchi
by
8.1k points