{"course":{"slug":"python-for-ai","title":"Python, from Zero, for AI","url":"https://addaly.com/learn/python-for-ai","level":"beginner","track":"build"},"lesson":{"slug":"masks-views-and-copies","title":"Masks, where, and the slice that is not a copy","url":"https://addaly.com/learn/python-for-ai/masks-views-and-copies","position":73,"of":89,"minutes":8,"answer":"A boolean mask selects elements in one expression and replaces most loops; a basic slice of an array is a view onto the same memory so writing to it writes to the original.","keyIdea":"A boolean mask selects elements in one expression and replaces most loops; a basic slice of an array is a view onto the same memory so writing to it writes to the original, while a mask or fancy index returns a copy."},"body":{"format":"markdown","text":"## Selecting with a condition\n\n```python\nscores = np.array([0.91, 0.12, 0.77, 0.45, 0.98])\nmask = scores > 0.5\nmask                 # [ True, False,  True, False,  True]\nscores[mask]         # [0.91, 0.77, 0.98]\nmask.sum()           # 3 — True counts as 1\n```\n\nA comparison on an array produces a boolean array of the same shape, and indexing with it keeps the elements where it is `True`. Two lines replace a loop with an `if`, and they run at NumPy speed. Combine conditions with `&`, `|` and `~`, each side in brackets: `and`/`or` do not work on arrays, and forgetting the brackets makes `&` bind tighter than `>` and raise a confusing error:\n\n```python\nscores[(scores > 0.3) & (scores < 0.9)]      # [0.77, 0.45]\nscores[~mask]                                # [0.12, 0.45]\n```\n\nAssignment through a mask changes only the selected elements:\n\n```python\nscores[scores < 0.2] = 0.0\n```\n\nThat is the array form of \"zero out the weak scores\", and it is the pattern under clipping, thresholding, and replacing bad values with a sentinel.\n\n## `np.where`\n\n```python\nlabels = np.where(scores > 0.5, \"positive\", \"negative\")\n```\n\n`where(condition, a, b)` picks from `a` where the condition holds and `b` elsewhere, elementwise, broadcasting all three. With one argument it returns the *indices* where the condition is true (`np.where(scores > 0.5)[0]` gives `[0, 2, 4]`), which is what you need to map a match back to the row of a table it came from. `np.nonzero` is the same thing under a clearer name. `np.argwhere` returns them one per row for multi-dimensional arrays.\n\n`np.clip(a, lo, hi)` is the special case of \"no smaller than, no larger than\", and `np.nan_to_num` replaces `nan` and `inf` with numbers, for the aftermath of the previous lesson.\n\n## Fancy indexing\n\n```python\nidx = np.array([4, 0, 2])\nscores[idx]              # [0.98, 0.91, 0.77] — in the order you asked\n```\n\nIndexing with an integer array picks those positions, in that order, with repeats allowed. Combined with `argsort` it sorts one array by another:\n\n```python\norder = np.argsort(scores)[::-1]     # indices, largest first\nnames[order][:3]                     # names of the top three\n```\n\n`argsort` returns the permutation that would sort; applying it to a different array of the same length carries the ordering across. This is how the top-k results of a similarity search become the top-k documents: sort the scores, apply the permutation to the IDs. `np.argpartition(scores, -k)[-k:]` finds the top k without sorting everything, which matters once the array is millions long.\n\nTwo-dimensional fancy indexing takes one array per axis: `m[rows, cols]` with two equal-length arrays picks the elements at those `(row, col)` pairs, not the sub-grid. To get the sub-grid, use `np.ix_(rows, cols)`. This surprises everyone once.\n\n## Views and copies\n\nHere is the fact that separates people who have been bitten from people who have not. **A basic slice of a NumPy array is a view.** It does not copy; it is a window onto the same memory.\n\n```python\na = np.arange(10)\nb = a[2:5]\nb[0] = 99\na               # [0, 1, 99, 3, 4, ...]  — a changed\n```\n\nFor a list this would be a copy, as module 2 established. For an array, slicing with `:` or a step gives a view, because copying a slice of a hundred-million-element array every time would be ruinous. The view shares the data; `b.base is a` confirms it.\n\nMasks and fancy indexing, by contrast, **return copies**. `a[a > 5]` cannot be a view because the selected elements are not evenly spaced in memory. Writing to that result does nothing to `a`, but writing *through* the mask in a single statement, `a[a > 5] = 0`, does, because that is an assignment into `a`, not into a copy.\n\nThe trap in one line:\n\n```python\ntop = scores[:100]\ntop *= 0          # clears the first 100 of scores too\n```\n\nThe fix is `.copy()` when you mean a copy: `top = scores[:100].copy()`. `reshape` and `ravel` also return views when they can; `flatten` always copies. `arr.T` is a view. When in doubt, `np.shares_memory(a, b)` answers the question.\n\nThe same fact has a benefit: `a[:, 0] = 0` clears the first column of a matrix in place without allocating, and a function that receives a view of a large array can write results into it without a copy. Knowing which you have is the whole skill.\n\n## Contiguity and the cost of a strided view\n\nA view produced by `a[::2]` or `a.T` is not contiguous in memory. Most operations still work but run slower, and a few libraries refuse it. `np.ascontiguousarray(v)` makes a packed copy. If a routine that is usually fast is slow on a particular array, `v.flags[\"C_CONTIGUOUS\"]` is worth a look.\n\n## Try this now\n\nTake a random `(1000,)` array, zero everything below its median with a mask, and confirm the count with `mask.sum()`. Then take a slice, modify it, and watch the original change; repeat with `.copy()`. Finally, `argsort` it descending and pull the top five indices, then do the same with `argpartition`."},"check":{"question":"`top = scores[:100]` is taken from a `(10000,)` array, then `top *= 0` to clear it for reuse. Later, `scores.max()` for the first hundred items is zero. What happened?","options":[{"text":"`*=` on an array always broadcasts back to the array the slice was taken from, as a general rule of in-place operators, whereas `top = top * 0` would have been safe.","correct":false,"tempting":"In-place operators act on whatever object they are applied to; the question is what that object shares, not a rule about slices."},{"text":"NumPy caches the last slice taken and reuses it for `max()`, returning the stale cleared values.","correct":false,"tempting":"There is no slice cache; `max()` reads the array's actual memory, which was modified."},{"text":"A basic slice is a view on the same memory, so writing into `top` wrote into the first hundred elements of `scores`.","correct":true},{"text":"The slice was taken before `scores` was fully loaded, so the values were zero all along and the `*= 0` changed nothing.","correct":false,"tempting":"The array was complete; the zeros appeared because of the write, which is what a view makes possible."}]},"prev":{"slug":"dtypes-and-precision","title":"dtypes: what float16 costs, why int8 wraps round, and how to compare floats","url":"https://addaly.com/learn/python-for-ai/dtypes-and-precision"},"next":{"slug":"vectors-and-cosine-similarity","title":"Dot products and cosine similarity: one vector against a hundred thousand in a single line","url":"https://addaly.com/learn/python-for-ai/vectors-and-cosine-similarity"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Masks, where, and the slice that is not a copy', in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/masks-views-and-copies (Accessed: 21 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Masks, where, and the slice that is not a copy","courseTitle":"Python, from Zero, for AI","module":{"index":8,"slug":"numbers-in-bulk","title":"Numbers in bulk: NumPy, pandas and the vector under every model"},"answer":null,"keyIdea":"A boolean mask selects elements in one expression and replaces most loops; a basic slice of an array is a view onto the same memory so writing to it writes to the original, while a mask or fancy index returns a copy.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"selecting-with-a-condition","runs":[{"text":"Selecting with a condition"}]},{"t":"code","lang":"python","label":"Python","text":"scores = np.array([0.91, 0.12, 0.77, 0.45, 0.98])\nmask = scores > 0.5\nmask                 # [ True, False,  True, False,  True]\nscores[mask]         # [0.91, 0.77, 0.98]\nmask.sum()           # 3 — True counts as 1"},{"t":"p","runs":[{"text":"A comparison on an array produces a boolean array of the same shape, and indexing with it keeps the elements where it is "},{"text":"True","code":true},{"text":". Two lines replace a loop with an "},{"text":"if","code":true},{"text":", and they run at NumPy speed. Combine conditions with "},{"text":"&","code":true},{"text":", "},{"text":"|","code":true},{"text":" and "},{"text":"~","code":true},{"text":", each side in brackets: "},{"text":"and","code":true},{"text":"/"},{"text":"or","code":true},{"text":" do not work on arrays, and forgetting the brackets makes "},{"text":"&","code":true},{"text":" bind tighter than "},{"text":">","code":true},{"text":" and raise a confusing error:"}]},{"t":"code","lang":"python","label":"Python","text":"scores[(scores > 0.3) & (scores < 0.9)]      # [0.77, 0.45]\nscores[~mask]                                # [0.12, 0.45]"},{"t":"p","runs":[{"text":"Assignment through a mask changes only the selected elements:"}]},{"t":"code","lang":"python","label":"Python","text":"scores[scores < 0.2] = 0.0"},{"t":"p","runs":[{"text":"That is the array form of “zero out the weak scores”, and it is the pattern under clipping, thresholding, and replacing bad values with a sentinel."}]},{"t":"h2","id":"np-where","runs":[{"text":"np.where","code":true}]},{"t":"code","lang":"python","label":"Python","text":"labels = np.where(scores > 0.5, \"positive\", \"negative\")"},{"t":"p","runs":[{"text":"where(condition, a, b)","code":true},{"text":" picks from "},{"text":"a","code":true},{"text":" where the condition holds and "},{"text":"b","code":true},{"text":" elsewhere, elementwise, broadcasting all three. With one argument it returns the "},{"text":"indices","i":true},{"text":" where the condition is true ("},{"text":"np.where(scores > 0.5)[0]","code":true},{"text":" gives "},{"text":"[0, 2, 4]","code":true},{"text":"), which is what you need to map a match back to the row of a table it came from. "},{"text":"np.nonzero","code":true},{"text":" is the same thing under a clearer name. "},{"text":"np.argwhere","code":true},{"text":" returns them one per row for multi-dimensional arrays."}]},{"t":"p","runs":[{"text":"np.clip(a, lo, hi)","code":true},{"text":" is the special case of “no smaller than, no larger than”, and "},{"text":"np.nan_to_num","code":true},{"text":" replaces "},{"text":"nan","code":true},{"text":" and "},{"text":"inf","code":true},{"text":" with numbers, for the aftermath of the previous lesson."}]},{"t":"h2","id":"fancy-indexing","runs":[{"text":"Fancy indexing"}]},{"t":"code","lang":"python","label":"Python","text":"idx = np.array([4, 0, 2])\nscores[idx]              # [0.98, 0.91, 0.77] — in the order you asked"},{"t":"p","runs":[{"text":"Indexing with an integer array picks those positions, in that order, with repeats allowed. Combined with "},{"text":"argsort","code":true},{"text":" it sorts one array by another:"}]},{"t":"code","lang":"python","label":"Python","text":"order = np.argsort(scores)[::-1]     # indices, largest first\nnames[order][:3]                     # names of the top three"},{"t":"p","runs":[{"text":"argsort","code":true},{"text":" returns the permutation that would sort; applying it to a different array of the same length carries the ordering across. This is how the top-k results of a similarity search become the top-k documents: sort the scores, apply the permutation to the IDs. "},{"text":"np.argpartition(scores, -k)[-k:]","code":true},{"text":" finds the top k without sorting everything, which matters once the array is millions long."}]},{"t":"p","runs":[{"text":"Two-dimensional fancy indexing takes one array per axis: "},{"text":"m[rows, cols]","code":true},{"text":" with two equal-length arrays picks the elements at those "},{"text":"(row, col)","code":true},{"text":" pairs, not the sub-grid. To get the sub-grid, use "},{"text":"np.ix_(rows, cols)","code":true},{"text":". This surprises everyone once."}]},{"t":"h2","id":"views-and-copies","runs":[{"text":"Views and copies"}]},{"t":"p","runs":[{"text":"Here is the fact that separates people who have been bitten from people who have not. "},{"text":"A basic slice of a NumPy array is a view.","b":true},{"text":" It does not copy; it is a window onto the same memory."}]},{"t":"code","lang":"python","label":"Python","text":"a = np.arange(10)\nb = a[2:5]\nb[0] = 99\na               # [0, 1, 99, 3, 4, ...]  — a changed"},{"t":"p","runs":[{"text":"For a list this would be a copy, as module 2 established. For an array, slicing with "},{"text":":","code":true},{"text":" or a step gives a view, because copying a slice of a hundred-million-element array every time would be ruinous. The view shares the data; "},{"text":"b.base is a","code":true},{"text":" confirms it."}]},{"t":"p","runs":[{"text":"Masks and fancy indexing, by contrast, "},{"text":"return copies","b":true},{"text":". "},{"text":"a[a > 5]","code":true},{"text":" cannot be a view because the selected elements are not evenly spaced in memory. Writing to that result does nothing to "},{"text":"a","code":true},{"text":", but writing "},{"text":"through","i":true},{"text":" the mask in a single statement, "},{"text":"a[a > 5] = 0","code":true},{"text":", does, because that is an assignment into "},{"text":"a","code":true},{"text":", not into a copy."}]},{"t":"p","runs":[{"text":"The trap in one line:"}]},{"t":"code","lang":"python","label":"Python","text":"top = scores[:100]\ntop *= 0          # clears the first 100 of scores too"},{"t":"p","runs":[{"text":"The fix is "},{"text":".copy()","code":true},{"text":" when you mean a copy: "},{"text":"top = scores[:100].copy()","code":true},{"text":". "},{"text":"reshape","code":true},{"text":" and "},{"text":"ravel","code":true},{"text":" also return views when they can; "},{"text":"flatten","code":true},{"text":" always copies. "},{"text":"arr.T","code":true},{"text":" is a view. When in doubt, "},{"text":"np.shares_memory(a, b)","code":true},{"text":" answers the question."}]},{"t":"p","runs":[{"text":"The same fact has a benefit: "},{"text":"a[:, 0] = 0","code":true},{"text":" clears the first column of a matrix in place without allocating, and a function that receives a view of a large array can write results into it without a copy. Knowing which you have is the whole skill."}]},{"t":"h2","id":"contiguity-and-the-cost-of-a-strided-view","runs":[{"text":"Contiguity and the cost of a strided view"}]},{"t":"p","runs":[{"text":"A view produced by "},{"text":"a[::2]","code":true},{"text":" or "},{"text":"a.T","code":true},{"text":" is not contiguous in memory. Most operations still work but run slower, and a few libraries refuse it. "},{"text":"np.ascontiguousarray(v)","code":true},{"text":" makes a packed copy. If a routine that is usually fast is slow on a particular array, "},{"text":"v.flags[\"C_CONTIGUOUS\"]","code":true},{"text":" is worth a look."}]},{"t":"h2","id":"try-this-now","runs":[{"text":"Try this now"}],"role":"try"},{"t":"p","runs":[{"text":"Take a random "},{"text":"(1000,)","code":true},{"text":" array, zero everything below its median with a mask, and confirm the count with "},{"text":"mask.sum()","code":true},{"text":". Then take a slice, modify it, and watch the original change; repeat with "},{"text":".copy()","code":true},{"text":". Finally, "},{"text":"argsort","code":true},{"text":" it descending and pull the top five indices, then do the same with "},{"text":"argpartition","code":true},{"text":"."}]}],"check":{"question":[{"text":"top = scores[:100]","code":true},{"text":" is taken from a "},{"text":"(10000,)","code":true},{"text":" array, then "},{"text":"top *= 0","code":true},{"text":" to clear it for reuse. Later, "},{"text":"scores.max()","code":true},{"text":" for the first hundred items is zero. What happened?"}],"options":[{"text":[{"text":"*=","code":true},{"text":" on an array always broadcasts back to the array the slice was taken from, as a general rule of in-place operators, whereas "},{"text":"top = top * 0","code":true},{"text":" would have been safe."}],"correct":false,"tempting":[{"text":"In-place operators act on whatever object they are applied to; the question is what that object shares, not a rule about slices."}]},{"text":[{"text":"NumPy caches the last slice taken and reuses it for "},{"text":"max()","code":true},{"text":", returning the stale cleared values."}],"correct":false,"tempting":[{"text":"There is no slice cache; "},{"text":"max()","code":true},{"text":" reads the array’s actual memory, which was modified."}]},{"text":[{"text":"A basic slice is a view on the same memory, so writing into "},{"text":"top","code":true},{"text":" wrote into the first hundred elements of "},{"text":"scores","code":true},{"text":"."}],"correct":true,"tempting":null},{"text":[{"text":"The slice was taken before "},{"text":"scores","code":true},{"text":" was fully loaded, so the values were zero all along and the "},{"text":"*= 0","code":true},{"text":" changed nothing."}],"correct":false,"tempting":[{"text":"The array was complete; the zeros appeared because of the write, which is what a view makes possible."}]}],"order":[0,1,3,2],"why":null},"prev":{"slug":"dtypes-and-precision","title":"dtypes: what float16 costs, why int8 wraps round, and how to compare floats","minutes":9},"next":{"slug":"vectors-and-cosine-similarity","title":"Dot products and cosine similarity: one vector against a hundred thousand in a single line","minutes":9}}}