1

In Python 3, I want to define a function that takes in a list a, does some operations and then returns some property of a. The problem is that I want a to stay unchanged.

Take for example the following code

def test(a):
    a.remove(1)
    return max(a)


When I run this, I get:

>>> b = [0,1,2,3]
>>> test(b)
3
>>> b
[0,2,3]

whereas I want b to stay unchanged

>>> b
[0,1,2,3]


I find this rather confusing, as Python does leave floats, ints, ... unchanged when being passed to a function.
Can anyone please explain what's going on? And what should I do to avoid this issue?

Thanks in advance

Jonas De Schouwer
  • 755
  • 1
  • 9
  • 15

1 Answers1

0

The list.remove method alters the list in-place. If you don't want the given list to change you can make a copy of the list first instead:

def test(a):
    a = a[:]
    a.remove(1)
    return max(a)
blhsing
  • 91,368
  • 6
  • 71
  • 106