[Tutor] global list
Gerardo Juárez
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[1] = x
>
> mutate_part(200)
>
> 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,
>
> -Denis
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
Hi,
Try out this modified version of the example you provide:
def mutate(x):
global y
y = x + 1
a[1] = x
a = [1, 2, 3]
y = 0
mutate(200)
print a
print y
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
it behaves
differently (spans across scopes). A more detailed answer can be found here:
http://stackoverflow.com/questions/4630543/defining-lists-as-global-variable-in-python
Of course, I would limit this practice to *very* small programs, since
anything beyond
50 lines should have more structure and you can use either modular
programming or
OOP, which is the preferred practice today to structure complex
applications.
Gerardo
More information about the Tutor
mailing list