diff options
-rw-r--r-- | doc/source/reference/arrays.indexing.rst | 11 | ||||
-rw-r--r-- | doc/source/user/quickstart.rst | 11 | ||||
-rw-r--r-- | numpy/doc/indexing.py | 4 |
3 files changed, 25 insertions, 1 deletions
diff --git a/doc/source/reference/arrays.indexing.rst b/doc/source/reference/arrays.indexing.rst index 3a319ecca..0c0c8dff6 100644 --- a/doc/source/reference/arrays.indexing.rst +++ b/doc/source/reference/arrays.indexing.rst @@ -57,6 +57,17 @@ interpreted as counting from the end of the array (*i.e.*, if All arrays generated by basic slicing are always :term:`views <view>` of the original array. +.. note:: + + NumPy slicing creates a :term:`view` instead of a copy as in the case of + builtin Python sequences such as string, tuple and list. + Care must be taken when extracting + a small portion from a large array which becomes useless after the + extraction, because the small portion extracted contains a reference + to the large original array whose memory will not be released until + all arrays derived from it are garbage-collected. In such cases an + explicit ``copy()`` is recommended. + The standard rules of sequence slicing apply to basic slicing on a per-dimension basis (including using a step index). Some useful concepts to remember include: diff --git a/doc/source/user/quickstart.rst b/doc/source/user/quickstart.rst index 5ef8b145f..262f53c1c 100644 --- a/doc/source/user/quickstart.rst +++ b/doc/source/user/quickstart.rst @@ -884,6 +884,17 @@ The ``copy`` method makes a complete copy of the array and its data. [ 8, 10, 10, 11]]) +Sometimes ``copy`` should be called after slicing if the original array is not required anymore. +For example, suppose ``a`` is a huge intermediate result and the final result ``b`` only contains +a small fraction of ``a``, a deep copy should be made when constructing ``b`` with slicing:: + + >>> a = np.arange(int(1e8)) + >>> b = a[:100].copy() + >>> del a # the memory of ``a`` can be released. + +If ``b = a[:100]`` is used instead, ``a`` is referenced by ``b`` and will persist in memory +even if ``del a`` is executed. + Functions and Methods Overview ------------------------------ diff --git a/numpy/doc/indexing.py b/numpy/doc/indexing.py index 087a688bc..f80d6c29e 100644 --- a/numpy/doc/indexing.py +++ b/numpy/doc/indexing.py @@ -93,7 +93,9 @@ well. A few examples illustrates best: :: [21, 24, 27]]) Note that slices of arrays do not copy the internal array data but -only produce new views of the original data. +only produce new views of the original data. This is different from +list or tuple slicing and an explicit ``copy()`` is recommended if +the original data is not required anymore. It is possible to index arrays with other arrays for the purposes of selecting lists of values out of arrays into new arrays. There are |