[Python] Why is my list not updating inside a function in Python?

Discussão em 'Python' iniciado por Stack, Agosto 29, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to modify a list inside a function, but the changes don't seem to persist outside the function. Here's a simplified version of my code:

    def update_list(my_list):
    my_list = my_list + [4, 5]

    original_list = [1, 2, 3]
    update_list(original_list)
    print(original_list)


    What I tried:

    I defined a function that takes a list and attempts to add elements to it using my_list = my_list + [4, 5]. I then passed an existing list [1, 2, 3] to the function and expected the function to modify it.

    What I expected:

    I expected the original list to be updated to [1, 2, 3, 4, 5] after calling the function.

    What actually happened:

    The list remained [1, 2, 3] after the function call. The changes didn’t persist outside the function.

    Continue reading...

Compartilhe esta Página