Skip to content

Commit 267b0fd

Browse files
committed
Mention view only in solution of ex3
1 parent 5b73b47 commit 267b0fd

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

content/numpy.rst

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -266,18 +266,30 @@ Exercises 3
266266
::
267267

268268
a = np.eye(4)
269-
b = a[:,0]
269+
b = a[:, 0]
270270
b[0] = 5
271271

272-
- **View vs copy** Try out above code. How does ``a`` look like before ``b`` has changed and after? How could it be avoided?
272+
Try out the above code.
273+
274+
- How does ``a`` look like before ``b`` has changed and after?
275+
- How could it be avoided?
273276

274277
.. solution:: Solution: Numpy-3
275278

276-
- **View vs copy** The change in ``b`` has also changed the array ``a``!
277-
This is because ``b`` is merely a view of a part of array ``a``. Both
278-
variables point to the same memory. Hence, if one is changed, the other
279-
one also changes. If you need to keep the original array as is, use
280-
``np.copy(a)``.
279+
**View vs copy**: The change in ``b`` has also changed the array ``a``!
280+
This is because ``b`` is merely a *view* or a *shallow copy* of a part of array ``a``. Both
281+
variables point to the same memory. Hence, if one is changed, the other
282+
one also changes.
283+
284+
In this example, if you need to keep the original array as is, use
285+
:func:`np.copy(a) <numpy.copy>` or ``np.copy(a[:, 0])``
286+
to create a new *deep copy* of the whole or a slice of array respectively,
287+
before updating ``b``.
288+
289+
.. seealso::
290+
291+
NumPy's documentation on :numpy:ref:`quickstart.copies-and-views`
292+
281293

282294

283295
Types of operations

0 commit comments

Comments
 (0)