In python function arguments are passed by object reference. This means the simplest code to modify a list will modify the object itself.
a = [1,2,3]
def remove_one(b):
b.remove(1)
remove_one(a)
print(a)
The method remove_one returns nothing. If that was a public method one has to assume it will modify the object and isn't thread safe inside the method.
A second approach would be to structure the code snippet like this:
a = [1,2,3]
def remove_one(b):
b.remove(1)
return(b)
print(remove_one(a[:]))
Here the content of a wasn't modified and a new list is returned. This puts a lot of responsibility on the method caller.
Then again list comprehensions, the pythonic approach of modifying list contents always create a new object.
a = [1,2,3]
def remove_one(b):
b = [num for num in b if b!=1]
return(b)
print(remove_one(a))
It isn't clear to me if there is a "pythonic" way to do it so I'll make some assumptions to be challenged:
- It's safer to assume that a function taking a mutable object will modify it's content
- There is a reason why list comprehensions don't also directly modify the object. I just don't know it
- The "pythonic" way to write functions that use list comprehensions to modify the mutable argument isn't clear