scope, function, mutable

gusarer at gmail.com gusarer at gmail.com
Tue Dec 4 11:55:44 CET 2012


Hi,

What is the appropriate definition for the following behavior in Python 2.7
(see code below).
Both functions have assignment in it (like "x = ") so I assume, that x is a
local variable in both functions.
Also I thought this rule doesn't depend on WHERE in this function we find
the assignment.

But in both functions x becomes local variable only AFTER assignment, so in
f2 x[1] = 99 changes the global varialble (btw, x[3] = 99 doesn't).

def f1(x):
    x = [44] + x[1:]
    x[1] = 99

def f2(x):
    x[1] = 99
    x = [44] + x[1:]
    x[3] = 99

t = [1,2,3,4,5,6,7]
f1(t)
print t                            # [1, 2, 3, 4, 5, 6, 7]
t = [1,2,3,4,5,6,7]
f2(t)
print t                            # [1, 99, 3, 4, 5, 6, 7]

Thank you.

Roman Gusarev.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20121204/547236f8/attachment.html>


More information about the Python-list mailing list