Do NumPy arrays and lists get modified in Python functions? If yes, then how to take care that the values are not modified?
CodePudding user response:
Yes, those objects are mutable.
Be careful to write pure functions: pass in what the function needs and return what it produces. Don't use global variables and be careful not to produce side-effects if possible (plotting and printing things is okay, if that's the goal of the function). If you need to mutate an object in-place, make a copy of it inside the function. Aim for calling code that looks like this:
transformed_list = transform_function(original_list)
The original_list
object should be unchanged after this operation. This is how most Pandas and NumPy code works, so it's how most people expect other code to work too.
CodePudding user response:
Do NumPy arrays and lists get modified in Python functions?
Yes. In Python a function can change its mutable arguments. (In Python, you should generally keep in mind whether a type is mutable or immutable for this reason.)
If yes, then how to take care that the values are not modified?
This isn't necessary. It is also often inefficient, especially for large numeric arrays. Even in pure Python, some built-in function, such as sort
, mutate their arguments. On the Numpy side of things, even simple functions like add
often have a mechanism to do the calculation in-place, without creating a new array.
Instead, in Python the standard is: if a function mutates the arguments then is should return None
.