Search code examples
pythonlistsubroutinefunction-parameter

python: changing list value in sub-routine


I have a simple example. The function test_list_change should change the list passed to it as a parameter. And inside this function there is a call to sub-routine test_list_change_2 which should change the same list.

The problem is, that the result list doesn't contain changes made by the test_list_change_2 subroutine

Why it could be?

Here is the example:

def test_list_change(lst):
    if len(lst) < 3:
        lst.append("the last one")
        test_list_change_2(lst)

def test_list_change_2(lst):
    lst = ["the very last one"]

string_list = ["first", "another one"]
test_list_change(string_list)
print (string_list)

The output:

['first', 'another one', 'the last one']


Solution

  • You need to actually change the original list/object:

    def test_list_change(lst):
        if len(lst) < 3:
            lst.append("the last one")
            test_list_change_2(lst)
    
    def test_list_change_2(lst):
        lst[:] = ["the very last one"] # changes original list object
    
    string_list = ["first", "another one"]
    test_list_change(string_list)
    print (string_list)
    ['the very last one']
    

    If you want to change around the elements:

    def test_list_change_2(lst):
        lst[:-1] = ["the very last one"]
        lst[:] = lst[::-1]
    
    string_list = ["first", "another one"]
    test_list_change(string_list)
    print (string_list)
    ['the last one', 'the very last one']
    

    You can manipulate the list whatever way you like but you need to actually refer to the original list object, reassigning a name won't change the lst it will just assign that name to another object.