Perhaps someone can explain it better than me, but when you do the following:
print V
Python knows this variable isn't defined in your functions scope, and so it checks the global scope, and prints it.
If you were to do instead
V=5
Python knows this variable isn't defined in your functions scope, so it goes ahead and creates it (now it over-shadows V
at the global scope). There is different behaviour between writing a variable and reading it.
Now compare this to a list:
L[1]=22
This is similar to print V
. Why? Because Python needs to find where L is defined in memory, and then modifies its second index. This is a read
followed by a write
, whereas print V
is simply a read
from memory.
When your operation needs to do a read
first, it will find the reference that was defined at the outer scope, and that is why you see a difference between V=55
and L[1]=22
.
When your operation is a write
first, it will create a new variable in the function scope unless you have that variable marked as a global
. Then it will modify that global
instead.