Given this source list:
source_list = [2, 3, 4]
and this function:
def function(list_in):
list_in.append(5)
list_in.insert(0, 1)
return list_in
As expected, I get:
>>> function(source_list)
[1, 2, 3, 4, 5]
But if I call the variable source_list outside of the function I still get:
>>> source_list
[1, 2, 3, 4, 5]
Is there an alternative way of modifying (specifically appending/prepending to) a list within a function such that the original list is not changed?
If you have access to the function, you can copy the list passed:
like this:
def function(list_in_): # notice the underscore suffix
list_in = list_in_[:] # copy the arg into a new list
list_in.append(5)
list_in.insert(0, 1)
return list_in # return the new list
otherwise you can call the function with a copy of your source_list
, and decide if you want a new list, or if you prefer the source_list
mutated, as demonstrated by @tdelaney