0

In Python, is there a difference between the following two codes both of which gives the same result c = [0,-10]?

def foo1():
    a = [0,1]

    def foo2():
        a[1] = -10

    foo2()
    return a


c = foo1()

and

def foo1():
    a = [0,1]

    def foo2(b):
        b[1] = -10

    foo2(a)
    return a


c = foo1()

Some commentator suggests this is answered by this question. But it does not since my question asks about the passing of variables through an inner function whilst the linked question does not.

14
  • Does this answer your question? Understanding variable scope in nested functions in Python Commented Jul 23, 2020 at 22:39
  • 2
    Well, it's doing the same thing in two different ways. Commented Jul 23, 2020 at 22:45
  • @Jab: It does not answer my question. It shows the difference in the scope of the variables but says nothing about transmitting variables. Commented Jul 23, 2020 at 22:52
  • @juanpa.arrivillaga: You are saying option 1 is better because it is more succinct, right? Commented Jul 23, 2020 at 22:53
  • What exactly do you mean by "transmitting" You're not "transmitting" anything here. You're essentially asking if there's a difference between passing a variable to a function vs using the local variable you would have passed anyway which both examples have access to already. This is not a very good example as there's no need to use the nested function here at all. Commented Jul 23, 2020 at 22:55

1 Answer 1

0

In the first, a is a free variable whose value is taken from the nearest enclosing scope (in this case, the scope of foo1) that defines a.

In the second, b is a local variable initialized using the argument passed to foo2 when it is called, which is the variable a defined in foo1.

In each case, you assign -10 to the second "slot" of the same list.

Sign up to request clarification or add additional context in comments.

2 Comments

But both 'a' and 'b' in 'foo2' point to and are merely two names of the same variable, right?
Right, though the second foo2 has the flexibility to be called with a different argument. Your first foo2 is hard-coded to refer to a from the enclosing scope. Put another way, the object that foo2's free a refers to is fixed at the time foo2 is defined. The object that foo2's local variable b refers to is determined when foo2 is called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.