-2

For example, I have to write a function called '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 but all items in the input are distinct

Mmotrsg
  • 13
  • 2
  • 4
    Please see [How do I ask and answer homework questions?](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – azro Mar 19 '21 at 17:30
  • Share your tries, identify a specific problem to reach that, then ask about. You won't step up if you don't train – azro Mar 19 '21 at 17:31

2 Answers2

0

Replaces the index of the old item by a new item

lst[lst.index(old)] = new
lst - your list

old - old element

new - new element

Oh also check out this link: https://www.google.com/search?q=python+lists&oq=python+lists&aqs=chrome.0.69i59j69i60l3.1754j0j1&sourceid=chrome&ie=UTF-8

Kral
  • 189
  • 1
  • 10
0

Try this:

lst = [1, 5, 3, 9, 8]

def replace(lst, old, new):
    if old in lst:
        if new not in lst:
            lst[lst.index(old)] = new

            return lst

Firstly, it checks to see if the old value actually is in the list. If it is, then it checks if the new value is not in the list.

Assuming, these are true, it then changes the old value to the new value with the line: lst[lst.index(old)] = new.

Finally, it returns the new list with the modified value!

The Pilot Dude
  • 2,091
  • 2
  • 6
  • 24