Why is numpy.ravel returning a copy?

Viewed 2646

In the following example:

>>> import numpy as np
>>> a = np.arange(10)
>>> b = a[:,np.newaxis]
>>> c = b.ravel()
>>> np.may_share_memory(a,c)
False

Why is numpy.ravel returning a copy of my array? Shouldn't it just be returning a?

Edit:

I just discovered that np.squeeze doesn't return a copy.

>>> b = a[:,np.newaxis]
>>> c = b.squeeze()
>>> np.may_share_memory(a,c)
True

Why is there a difference between squeeze and ravel in this case?

Edit:

As pointed out by mgilson, newaxis marks the array as discontiguous, which is why ravel is returning a copy.

So, the new question is why is newaxis marking the array as discontiguous.

The story gets even weirder though:

>>> a = np.arange(10)
>>> b = np.expand_dims(a,axis=1)
>>> b.flags
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False
>>> c = b.ravel()
>>> np.may_share_memory(a,c)
True

According to the documentation for expand_dims, it should be equivalent to newaxis.

2 Answers
Related