[Numpy-discussion] Determine if two arrays share references

Robert Kern robert.kern@gmail....
Wed Feb 10 22:01:57 CST 2010

On Wed, Feb 10, 2010 at 21:41, Keith Goodman <kwgoodman@gmail.com> wrote:
> Here are two arrays that share references:
>>> x = np.array([1,2,3])
>>> y = x[1:]
> and here are two that don't:
>>> x = np.array([1,2,3])
>>> y = x[1:].copy()
> If I didn't know how the arrays were constructed, how would I
> determine if any elements in the two arrays share reference?

It is hard to do this 100% accurately given the full variety of
strided memory, but:

In [2]: np.may_share_memory?
Type:           function
Base Class:     <type 'function'>
String Form:    <function may_share_memory at 0x1565bb0>
Namespace:      Interactive
Definition:     np.may_share_memory(a, b)
    Determine if two arrays can share memory

    The memory-bounds of a and b are computed.  If they overlap then
    this function returns True.  Otherwise, it returns False.

    A return of True does not necessarily mean that the two arrays
    share any element.  It just means that they *might*.

One example where this function returns True when a 100% accurate
function would return False is x[::2] and x[1::2].

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco

More information about the NumPy-Discussion mailing list