Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #34214

scope, function, mutable

Date 2012-12-04 14:55 +0400
Subject scope, function, mutable
From gusarer@gmail.com
Newsgroups comp.lang.python
Message-ID <mailman.455.1354618548.29569.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

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.

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

scope, function, mutable gusarer@gmail.com - 2012-12-04 14:55 +0400
  Re: scope, function, mutable Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-12-04 11:32 +0000
  Re: scope, function, mutable Jussi Piitulainen <jpiitula@ling.helsinki.fi> - 2012-12-04 13:54 +0200

csiph-web