title: Functions and numpy array preallocation
body: <p>How to optimize functions involving numpy arrays? </p>
  
  <p>Use case:</p>
  
  <pre><code>def create_array_and_fill(a, b, N):
      res = np.zeros(N, N)
  
      res[0] = a
      res[-1] = b
  
      return res
  
  c = create_array_and_fill(5, 9, 100)
  </code></pre>
  
  <p>But then, sometimes, I know beforehand the maximum size of all arrays that I need to use (say for testing purposes), so what's the best way to go? Should I preallocate and what is the best way to do so? For example, can I pass a preallocated array to a function so that the function just updates it instead of returning a new one?</p>
  
  <p>My first ideas is as follows but, of course, it comes with a cost, I have to change all my function signatures now.</p>
  
  <pre><code>def create_array_and_fill(a, b, N, res):
  
      res[0] = a
      res[-1] = b
  
      # No more return here?
  
  c = np.zeros(N, N)
  create_array_and_fill(a, b, N, c) 
  </code></pre>