[Tutor] global list
gerardojuarez at buyteknet.info
Thu Apr 24 02:26:02 CEST 2014
On 04/23/2014 06:46 PM, Denis Heidtmann wrote:
> In a coursera python course video the following code was presented:
> a = [4,5,6]
> def mutate_part(x):
> a = x
> The presenter said something like "a is a global variable, so a becomes
> [4,200,6] after running mutate_part(200)."
> Indeed it does, but why does this work without specifying a as global
> within mutate()?
> My thinking was that an "undefined" error should have been raised.
> Help me understand. Thanks,
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
Try out this modified version of the example you provide:
y = x + 1
a = x
a = [1, 2, 3]
y = 0
Both, 'a' and 'y' will be modified, but if you comment out global, 'y'
will not change.
In a few words, assigning a[k] = value is technically a method call, and
differently (spans across scopes). A more detailed answer can be found here:
Of course, I would limit this practice to *very* small programs, since
50 lines should have more structure and you can use either modular
OOP, which is the preferred practice today to structure complex
More information about the Tutor