Exercise: Passing function arguments

When programming mathematical algorithms, it is important to know if unnecessary copying is being done by your program. Copying large matrices is expensive. Consider this simple function, where w could be a matrix or a vector or a list or a string etc.

In [1]:
def twice(w):
    """Replace w by 2*w"""
    w *= 2

Consider a scenario where you make an object v and then send it to this function, like in this example:

In [2]:
v = [2, 5, 1]
twice(v)

Task: Your task is to determine if v is being copied when you call twice(v) for some v. In other words, is a deep copy of v being implicitly made by python when you send v as an argument to twice? Answer this for at least two cases:

  • v is a numpy array
  • v is a string

Explain your observations.