Can anyone explain the following result in Python?
When I run the following snippet of code, Python throws an error stating that before the link assignment was specified x:
x = 1
def increase_x():
x += 1
increase_x()
The solution, of course, should include a line global xafter the function declaration for increase_x.
However, there is no error running this next snippet of code, and the result is what you expect:
x = [2, -1, 4]
def increase_x_elements():
for k in range(len(x)):
x[k] += 1
increase_x_elements()
Is it because integers are primitives in Python (not objects), and so xin the first fragment is it a primitive stored in memory, and xin the second fragment it refers to a pointer to a list object?
source
share