if in the local scope you try to assign to a name that is not being declared global, then it will be local (that is what happening in the first snippet)
In the second snippet you assign to a and b, so they again are local names. For c, you don't assign to c, you assign new value to element with index 0. That's the difference, you don't create new name c within the local scope, so it uses the one from the global scope. see the difference
In the second snippet you assign to a and b, so they again are local names. For c, you don't assign to c, you assign new value to element with index 0. That's the difference, you don't create new name c within the local scope, so it uses the one from the global scope. see the difference
a = 20 b = 30 c = [1, 2, 3] print(f'outside, id: {id(c)}, c:{c}') def demo(): a = 21 b = 31 c = [4, 5, 6] print(f'inside, id: {id(c)}, c:{c}') c[0] = 7 print(f'inside, id: {id(c)}, c:{c}') demo() print(f'outside, id: {id(c)}, c:{c}')
Output:outside, id: 139836028387528, c:[1, 2, 3]
inside, id: 139836028387592, c:[4, 5, 6]
inside, id: 139836028387592, c:[7, 5, 6]
outside, id: 139836028387528, c:[1, 2, 3]
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs