Like this:
li = [1, 2, 3]
def change(l):
l[:] = [1, 2, 10]
change(li)
print li # [1, 2, 10]
The reason your approach does not work is that in python, variables are simply names that reference objects. When you write l = [1, 2, 10]
you're re-binding the name l
to refer to the new list you've just created, the old list is unchanged and still referred to by the global variable li
.
The above code instead modifies the object pointed to by l
by using slice assignment.
As mgilson indicates in his answer, you should make it very clear that the function actually modifies the passed argument in-place. If not, an unsuspecting programmer might pass it a list he intends to use as-is later, only to discover that everything in it has been lost. Giving your function a name indicating modification (like you've done) and not returning anything from it are both common indicators of such functions, like for instance random.shuffle
.
To achieve the same effect for a dict, the documentation tells us that this will do:
def change_dict(d):
d.clear() # Empty dict
d.update({"a": 3, "b": 9})