0
a = 1.111111
b = ["a", "b"]


def adder(x, y):
    x = x *100000
    y[0] = "Herman"
    return x, y

print a
print b
print ""

adder(a,b)

print a # 1.111111 - has not updated
print b # ['Herman', 'b'] - has updated even if list is in gobal scope

Is Scope the same for lists and vars and other objects in Python? In the test above, the var a was not updated when I called/invoked the function adder, however, the list was updated. This would imply that global vars are not changeable from within functions, but that lists and other data container objects like dictionaries are.

Is that correct? Is there any easy way to model this idea in of scope mentally in my head?

  • 3
    It's not about scope. It's about mutability. It so happens that integers are not mutable while lists _are_. – cs95 Sep 05 '17 at 02:48
  • 3
    Yes, scope works the same way for all variables. There’s a big difference between `y[0] = "Herman"` and `y = ["Herman"]`. – Ry- Sep 05 '17 at 02:48
  • https://stackoverflow.com/a/534509/707111 – Ry- Sep 05 '17 at 02:51
  • No, this has nothing to do with scope. Please see Ned Batchelder's [facts and Myths about Python Names and Values](https://nedbatchelder.com/text/names.html) – juanpa.arrivillaga Sep 05 '17 at 04:30

2 Answers2

0

Whenever you pass a list to the function you are passing its address and so it can be updated in a function while for a variable you need to pass it by reference for it to be updated successfully.

Daniyal Ahmed
  • 715
  • 5
  • 11
  • This is quite unclear, a variable may be anything, including a list, and how would you pass a variable assigned to `0` "by reference"? – Julien Sep 05 '17 at 03:08
  • This is incorrect. All variables are treated the same, and there is no pass-by-reference semantics in Python. – juanpa.arrivillaga Sep 05 '17 at 04:27
0

Variables (re)defined within a function are local by default. x in your case falls in this category. But y[0] = "Herman" is not redefining y, it's mutating it by reassigning its first element. Thus it's not considered local.

Julien
  • 13,986
  • 5
  • 29
  • 53