Custom Search

Friday, March 20, 2015

python why List and Dictionaries are automatically global?


  
>>> #changing a list entry is like calling a member function on the list.
... #For example a[3]=100 is Equal to a.__setitem__(3,100)
...
>>> #Without global, an assignment creates a new local.
...
>>> #In Python, if you do not assign to a variable inside a function it
... #will look for that variable in more global scopes until it finds it.
...
>>> a = range(5)
>>> def mutate(a):
...     a[3] = 100

...
>>> mutate(a)
>>> print a[3]
100
>>>
>>>
>>>
>>> a = range(5)
>>> def mutate(b):
...     a[3] = 100

...     #Equal to a.__setitem__(3,100) 
...
>>> mutate(a)
>>> print a[3]
100
>>>
>>>
>>>
>>> a = range(5)
>>> def mutate(b):
...     b[3] = 100
...
>>> mutate(a)
>>> print a[3]
100



1 comment:

  1. http://stackoverflow.com/questions/6329499/in-python-why-is-list-automatically-global

    ReplyDelete