Copying numpy arrays vs. copying lists

Today’s daily pitfall celebrates array copying. In a previous post, we talked about copying lists. If you’re using a numpy array (ndarray), however, the correct way to do it is using numpy’s convenient copy function.

import numpy as np
new_ndarray = np.copy(old_ndarray)

If you try using standard list copying methods – it won’t work, but Python won’t throw an exception, either. Took 30 minutes of algorithm debugging mixed in with a healthy dose of profanity before I tracked down the problem.

new_ndarray = old_ndarray[:]  # please don't do this