Search code examples
pythonlistdeep-copyundo

Undo function using self made "deepcopy"?


I want to create an undo() function that undoes the last operation in python, so I just deepcopied the list before any modifications were made during whatever function to another list (I made a bootleg deepcopy by myself), called undolist, and then when I call undo() I just pop the last element from the undolist

I know there are other more efficient ways of doing this, but given my time constraints and my mental in-capabilities I don't think I could turn this in.

However, it doesn't work. I am going to post an example of how I implemented the undo function and the bootleg deepcopy on a random function, since the code itself is super long and in another language

I hope I've made myself clear enough, if there are any misunderstandings I'll edit the post.

main_list = [list of lists that have elements in them]


def bootleg_deepcopy(main_list):
    new_list = []
    for x in main_list:
        nx = x[:]
        new_list.append(nx)
    return new_list
    
    
def delete_elements(main_list,user_input,undolist):
    #function that deletes elements from the list if a condition isn't met
    undolist.append(bootleg_deepcopy(main_list))
    main_list[:] = [element for element in main_list if not function_that_checks_something(whatever,something)]
    return main_list


def undo(main_list,undolist):
    try:
        main_list = undolist.pop()
    except Exception as ex:
        print(ex)
    return main_list

Solution

  • The solution was to use the slice operator(?) in the undo() function. I've edited it so that it includes the right code.

    def undo(main_list,undolist):
        try:
            main_list[:] = undolist.pop()
        except Exception as ex:
            print(ex)
        return main_list