I was writing a Python function yesterday to which I passed a list as an argument.
After manipulating the list I passed, I returned my desired value.
What was a little surprising to me was that the initial list itself got updated.
For example, consider the following:
>>> def return_new_list(old_list): old_list.append("new stuff") return old_list >>> my_list = ["a"] >>> print return_new_list(my_list) ['a', 'new stuff'] >>> print my_list ['a', 'new stuff']
I would have expected that the list "my_list" would still only have the original item, "a".
Instead, "my_list" itself has been altered per the function "return_new_list()".
So, after being flustered I stumbled onto this solution which uses the built-in "list()" function within the "return_new_list()" function.
>>> def return_new_list(old_list): old_list = list(old_list) # this seems to "fix" the "problem". old_list.append("new stuff") return old_list >>> my_list = ["a"] >>> print return_new_list(my_list) ['a', 'new stuff'] >>> print my_list ['a']
Of course, after searching for why this behavior is as it is, I found this page (see: "Mutable Default Arguments") which explained why Python does what it does and also presents a different way of dealing with the issue.
But, here too with the author's example code, it seems to work just fine to use the "list()" function within the function "append_to()".
>>> def append_to(element, to=): to = list(to) # I'm a new line! to.append(element) return to >>> print append_to(12)  >>> print append_to(42) 
Anyway, just thought I'd share.
I'd love to hear any opinions on why the "solution" I proposed works, isn't a good idea, or if ninja kicks the damn rabbit, etc.