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
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: