The following doubt is related to this question but a little different. The answer is not clear to me.
Consider a list x
that has to be modified. The following ipython session illustrates the point:
In [1]: x=[]
In [2]: x.append(2)
In [3]: x
Out[3]: [2]
In [4]: x=[] # able to start working on x again
In [5]: x
Out[5]: []
In [6]: def modify(x):
...: x.append(2)
...: print x
...: x=[] # does not throw errors
...:
In [7]: x=[]
In [8]: x.append(2)
In [9]: x.append(2)
In [10]: x # x is now a list
Out[10]: [2, 2]
In [11]: modify(x) # len(s) proportional to the number of times modify is called
[2, 2, 2]
In [12]: x
Out[12]: [2, 2, 2]
if x
, a list is a mutable object, why wasn't I able to modify it inside a function but was able to modify it on the command line? I thought it was related to the function being main but:
In [30]: def modify(x):
...: print __name__
...: x.append(2)
...: print x
...: x=[]
...: x=[1, 5, 7]
...:
the following session shows that name remains unchanged.
In [36]: print __name__
__main__
In [37]: x=[]
In [38]: modify(x)
__main__
[2]
# why is the name __main__ inside modify?
In [39]: modify(x)
__main__
[2, 2]