1

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?

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80

5 Answers5

2

If you are the caller of the function, you can copy first

new_list = function(source_list[:])

This has the advantage that the caller decides whether it wants its current list to be modified or not.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
1

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

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
0

You can use the copy() method on the list:

new_list = function(source_list.copy())
abhigyanj
  • 2,355
  • 2
  • 9
  • 29
0

Add just a line to your function:

   def function(list_n):
    #Do a copy of your list
    list_in = list_n.copy()
    list_in.append(5)
    list_in.insert(0, 1)
    return list_in
tdelaney
  • 73,364
  • 6
  • 83
  • 116
alphaBetaGamma
  • 653
  • 6
  • 19
0

Try this. Since the source list is modified while running the function in your code you are not able to retain the source list.

source_list = [2, 3, 4]
list_in=source_list.copy()
def function(list_in):
    list_in.append(5)
    list_in.insert(0, 1)
    return list_in
print(function(list_in))
print(source_list)
Vivs
  • 447
  • 4
  • 11