Apr-12-2020, 02:02 PM
I'm relatively new to learning Python. I've been reading "Mastering Python". In chapter 2 on Variables it provides an example similar to this:
Sorry if this seems elemental but this really stuck out to me as I was thinking about some other code that I have been working with.
Thanks.
Don
a = 20 b = 30 c = [1, 2, 3] def demo(): a = 21 b = 31 c = [4, 5, 6] demo()So after I run the program and do a print(a,b,c) I get the result as expected
>>> print(a,b,c) 20 30 [1, 2, 3]So I somewhat understand the scope of variables in reference to global versus local. The variables outside of the def are global and within the def are local. So far so good. But what if I do this:
a = 20 b = 30 c = [1, 2, 3] def demo(): a = 21 b = 31 c[0] = 5 demo()Now I get this result
>>> print(a,b,c) 20 30 [5, 2, 3]So if declaring a or b to new values in the def object doesn't change them why does c[0] = 5 change the global list of c without declaring it global within the def object?
Sorry if this seems elemental but this really stuck out to me as I was thinking about some other code that I have been working with.
Thanks.
Don