0

I'm making a program that will do some operations like add, insert, pop on a list of numbers. I have to also make an "undo" function and for that I thought about making a list in list to save up my list every step of the way but my tests are not working. Here's the code:

def backup(l):
        lbackup.append(list(l))

<-- here I save the list every step of the way by calling this function

> def undo(l):
>     l=lbackup[len(lbackup)-1] # here I give my list the previous list
>     del lbackup[len(lbackup)-1]  # here I delete the sublist from the history

My test:

def testUndo():
    add(lista, 1)
    backup(lista)
    add(lista, 2)
    backup(lista)
    add(lista,111111)
    print(lbackup)
    print(lista)
    undo(lista)
    print(lista)
    print(lbackup)

So I checked the inside of the Undo function and it's working! It actually changed the value of my list to what I wanted but once it left the function and got to the print after undo in the test... it had the same values again. I know lists are mutable and that might be a problem but is there anything I could do? Sorry if I wasnt clean enough.

Katie44
  • 29
  • 1
  • 10

1 Answers1

0

When you call, say, undo(lista), the l inside of undo may be the same list as lista, but assigning to l does not change lista. If instead you had undo return l, and assign the value returned by undo back to list, that would make the change you seem to want.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101