简体   繁体   中英

Python list scope outside a function

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

xxx = []
print foo(xxx)
print xxx

In this code you are calling foo() with the list you created outside the function, called xxx . But within the function, you are recursing to call foo() without parameters, so it modifies the list that was created at function definition time by the expression for the default argument value. (Importantly, this is the same list every time you call the function without supplying a value for that argument.)

Compare what happens when you define foo like this instead:

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

... and what happens when you define it like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM