Writing (and not) to global variable in Python

Viewed 391

Coming from much less dynamic C++, I have some trouble understanding the behaviour of this Python (2.7) code.

Note: I am aware that this is bad programming style / evil, but I would like to understand it non the less.

vals = [1,2,3]

def f():
    vals[0] = 5
    print 'inside', vals

print 'outside', vals
f()
print 'outside', vals

This code runs without error, and f manipulates the (seemingly) global list. This is contrary to my prior understanding that global variables that are to be manipulated (and not only read) in a function must be declared as global ....

On the other hand, if I replace vals[0] = 5 with vals += [5,6], execution fails with an UnboundLocalError unless I add a global vals to f. This is what I would have expected to happen in the first case as well.

Could you explain this behaviour?

Why can I manipulate vals in the first case? Why does the second type of manipulation fail while the first does not?

Update: It was remarked in a comment that vals.extend(...) works without global. This adds to my confusion - why is += treated differently from a call to extend?

3 Answers
Related