[Python] Python list scope outside a function

Discussão em 'Python' iniciado por Stack, Janeiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    I am having a problem which is hard to explain because there's a lot of code involve. So it boils down to the following problem.

    I am trying to access the list xxx outside the function foo but I am getting unexpected results. Can someone please explain why?

    Here's my function which I have created to show the problem:

    def foo(xxx = []):
    if len(xxx) == 5:
    return xxx
    xxx += [1]
    foo()
    return xxx


    If I run

    print foo()


    I get

    [1, 1, 1, 1, 1]


    which is what I expect.

    But I want the list xxx to be accessible outside foo. So, I am doing

    xxx = []
    print foo(xxx)
    print xxx


    Now I expect to get the list xxx to be

    [1, 1, 1, 1, 1]


    but what I am getting xxx to be, is

    [1]


    which is not what I expect.

    Can someone explain why? And is it possible to access the correct xxx outside foo without accessing it through the output of the function foo? The reason I want to do this is because in my actual code I am returning something other than in my function foo and making changes to xxx which I want to see after the foo has executed. I can make the function also return xxx every time but this will make my code unnecessarily bulky. But I am not sure if I am compromising the code quality. I don't know. Please suggest which ever way is the best.

    Thanks

    Continue reading...

Compartilhe esta Página