Copies and views
Overview
A view is an ndarray that references the same underlying data as another array. A copy owns its own storage and is independent from the original. Views are fast and memory-efficient, but changes to the base array are visible through the view.
Creating views
Most indexing and slicing operations return views:
You can also create views explicitly with view and slice. Use base to check whether an array is a view:
Copies: copy and deepCopy
Use these methods to detach from a view and get independent data:
copy()duplicates the underlying storage and preserves the current layout (offset/strides).deepCopy()materializes only the visible elements into a new contiguous array.
deepCopy() is usually the safer choice when you need a compact, standalone array or want to avoid copying data that is outside a view.
Views vs copies in common operations
Typical view-producing operations:
Indexing and slicing
view(...)andslice(...)transpose()andsqueeze()
Operations that always allocate new storage:
copy()anddeepCopy()flatten()cat(...)andmk.stack(...)
Operations like reshape() and unsqueeze() return views when the array is contiguous; otherwise they materialize a copy to keep data consistent.