Forums

List headaches copying, sorting inside functions

Why is it that within a function sometimes the function changes the list handed it, and other times is doesn't? For example the sort() method does not change the original list, but doing arithmetic on elements does? Also, it seems that making copies of lists change the original list too, which makes no sense at all. This is really driving me crazy.

When you assign in Python (a=b), you create a binding, not a second object.

If you want to copy, then you need to use the copy library.

See:

>>> a = [1,2,3]
>>> b = a
>>> b[1]
2
>>> b[1] = 4
>>> b
[1, 4, 3]
>>> a
[1, 4, 3]
>>> import copy
>>> a = [1,2,3]
>>> b = copy.copy(a)
>>> b
[1, 2, 3]
>>> b[1] = 4
>>> b
[1, 4, 3]
>>> a
[1, 2, 3]

You're right in that any python function is able to freely manipulate/change the variables that are passed to it.

Everything is an object in python, and you/functions may change parts of any mutable object that is passed to it. (there are particular python objects that are immutable- strings, tuples, ints, True/False/None)

So for example, if you pass a list [a, b, c] to a function. That function may add/remove items from the list. As rcs1000 says, you may instead create an actual copy of the list and pass that. But if a is not immutable and that function modifies it, you would still see the changes to a in the original list. In that case you want to do a deepcopy.