3

I wonder why reference variable(dict, list) is accessible from nested function while simple object is not.

In [1]: a = 1

In [2]: b = [1]

In [3]: c = {"c" : 1}

In [4]:

In [4]: def f():
   ...:         a = 2
   ...:         b[0] = 2
   ...:         c["c"] = 2
   ...:

In [5]: f()

In [6]:

In [6]: print a
1

In [7]: print b
[2]

In [8]: print c
{'c': 2}
chantal
  • 53
  • 3
  • Because integer is immutable while lists and dictionaries are mutable read http://stackoverflow.com/questions/8056130/immutable-vs-mutable-types-python. – Ankit Jaiswal Feb 23 '16 at 08:45

2 Answers2

1

Integer is immutable, that means when python execute

a=2 inside f()

It create a new local object. While list and dictionary is mutable, so it can be modified in place.

>>> a = 0
>>> id(a)
31367908
>>> ls = [1,2]
>>> id(ls)
50082760
>>> def f():
    a = 2
    print id(a)
    ls[0] = 5
    print id(ls)


>>> f()
31367884
50082760
AlokThakur
  • 3,599
  • 1
  • 19
  • 32
0

With statement a = 2 you are creating new local variable with value 2. However when you modify b[0] or c['c'] you are mutating global variable. If you have to deal with mutable types in function (work with them as with local variables) you have to initialize appropriate variable before mutating it:

def f():
  c = {}
  b = []
  c['c'] = 2
  b.append(1)

See Variables and scope chapter with great description of how scope works in python and get more info about mutable and immutable types.

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82