[Tutor] When is = a copy and when is it an alias

eryksun eryksun at gmail.com
Mon Jan 27 22:17:56 CET 2014


On Mon, Jan 27, 2014 at 9:07 AM, Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:
> On 27/01/2014 09:53, spir wrote:
>>
>> Note: your example is strongly obscured by using weird and rare features
>> that don't bring any helpful point to the actual problematic concepts
>> you apparently want to deal with.
>>
>
> Nothing weird and rare about it, just something from the numpy maths library
> and not pure Python.

NumPy arrays may seem weird to someone who expects a slice to create a
shallow copy of the data, in the way that slicing a `list` creates a
shallow copy:

    >>> a = [0, 2, 4]
    >>> b = a[:]

`b` is a copy of list `a`, so modifying `b` has no effect on `a`:

    >>> b[:] = [1, 3, 5]
    >>> a
    [0, 2, 4]

Slicing a NumPy array returns a new view on the data:

    a = np.array([0, 2, 4], dtype=object)
    b = a[:]

    >>> b.base is a
    True
    >>> b.flags.owndata
    False

The view shares the underlying data array, so modifying it also
changes the original:

    >>> b[:] = [1, 3, 5]
    >>> a
    array([1, 3, 5], dtype=object)

You have to ask for a `copy`:

    a = np.array([0, 2, 4], dtype=object)
    b = a.copy()

    >>> b.base is None
    True
    >>> b.flags.owndata
    True

    >>> b[:] = [1, 3, 5]
    >>> a
    array([0, 2, 4], dtype=object)


More information about the Tutor mailing list