A question on modification of a list via a function invocation
Ben Finney
ben+python at benfinney.id.au
Wed Aug 16 21:05:50 EDT 2017
Mok-Kong Shen <mok-kong.shen at t-online.de> writes:
> I don't yet understand. Why (by which rule of the language reference)
> should "alist=[30,60,90]" mean discarding the name's reference to the
> [1,2,3] list?
I think I understand that question, but I find it surprising.
What is your expectation of the following code?
foo = "spam"
foo = "beans"
print(foo)
What should ‘foo’ be bound to after the second assignment?
Your question seems to imply you expect that the ‘foo’ reference would
be bound to *both* of “"spam"” and “"beans"”, somehow. Is that right?
How would that work?
To answer the question: The semantics of an assignment statement are at
in the Python language reference.
Assignment statements are used to (re)bind names to values […]
If the target is an identifier (name): […] The name is rebound if it
was already bound.
<URL:https://docs.python.org/3/reference/simple_stmts.html#grammar-token-assignment_stmt>
A reference (a name is one kind of reference) can be bound to exactly
one object at any time.
> But then, since now the name alist is known to be global, why then in
> the next line of test2 the name is suddenly interpreted to be local?
The same section of the language reference discusses that.
In brief: The fact that the first use of a name, in the current scope,
is an assignment, means that the name is implicitly within that scope.
--
\ “Pinky, are you pondering what I'm pondering?” “Uh, I think so, |
`\ Brain, but we'll never get a monkey to use dental floss.” |
_o__) —_Pinky and The Brain_ |
Ben Finney
More information about the Python-list
mailing list