1D Slicing
Take a range of elements with start:stop:step — first N, last N, every k-th element and reversing an array.
Watch the lesson
1 video on CodeWithMunnaX
Indexing gives you one match. But questions like "Virat's first 5 matches", "the last 3 matches" or "every alternate match" need a range of elements. That is slicing.
Definition
Slicing is selecting a contiguous or evenly-stepped range of elements with the syntax
arr[start:stop:step]. It returns a new array object containing the elements from indexstartup to but not includingstop, jumpingsteppositions each time. In NumPy, the result is a view of the original data, not a copy.
- start — the first index included. If omitted, it starts at the beginning (or at the end when
stepis negative). - stop — the index where slicing stops; it is excluded. If omitted, it goes to the end (or to the beginning when
stepis negative). - step — how many positions to jump.
1by default;2= every other element; a negative step walks backwards. - View — the slice shares memory with the original array. Changing the slice changes the original (see Modifying Arrays via Indexing).
Syntax
python
arr[start:stop] # from start up to stop-1
arr[start:stop:step] # with a jump
arr[:stop] # from the beginning
arr[start:] # to the end
arr[::step] # whole array, every step-th element
arr[::-1] # whole array reversed| Parameter | Meaning | Default (step > 0) | Default (step < 0) |
|---|---|---|---|
start | first index to include | 0 | last element (-1) |
stop | index to stop at (excluded) | len(arr) (the end) | "before the first element" |
step | gap between chosen indexes; cannot be 0 | 1 | — |
Count of elements in arr[start:stop] (step 1) is simply stop - start. virat_runs[2:7] has 7 - 2 = 5 elements.
Example — first N, last N, a middle range
python
import numpy as np
virat_runs = np.array([72, 45, 88, 31, 64, 0, 103, 52, 19, 77, 41, 93, 28, 66])
print("First 5 matches :", virat_runs[:5])
print("Matches 3 to 7 :", virat_runs[2:7])
print("From match 10 :", virat_runs[9:])
print("Last 3 matches :", virat_runs[-3:])
print("All but last 2 :", virat_runs[:-2])text
First 5 matches : [72 45 88 31 64]
Matches 3 to 7 : [ 88 31 64 0 103]
From match 10 : [77 41 93 28 66]
Last 3 matches : [93 28 66]
All but last 2 : [ 72 45 88 31 64 0 103 52 19 77 41 93]How it works: "matches 3 to 7" are indexes 2, 3, 4, 5, 6 — so we write 2:7 because stop is excluded. -3: starts 3 from the end and runs to the end. :-2 stops before the second-last element.
Example — step and reversing
python
virat_runs = np.array([72, 45, 88, 31, 64, 0, 103, 52, 19, 77, 41, 93, 28, 66])
print("Every 2nd match (odd matches) :", virat_runs[::2])
print("Every 2nd match (even matches):", virat_runs[1::2])
print("Every 3rd match from match 1 :", virat_runs[0:14:3])
print("Reversed (latest first) :", virat_runs[::-1])
print("Last 4, newest first :", virat_runs[-1:-5:-1])text
Every 2nd match (odd matches) : [ 72 88 64 103 19 41 28]
Every 2nd match (even matches): [45 31 0 52 77 93 66]
Every 3rd match from match 1 : [ 72 31 103 77 28]
Reversed (latest first) : [ 66 28 93 41 77 19 52 103 0 64 31 88 45 72]
Last 4, newest first : [66 28 93 41]How it works: ::2 picks indexes 0, 2, 4, …; 1::2 picks 1, 3, 5, …. With step = -1 NumPy walks backwards, so [::-1] reverses the whole array. In [-1:-5:-1] it starts at the last element and stops before index -5, giving 4 elements.
Example — slicing never raises IndexError
python
virat_runs = np.array([72, 45, 88, 31, 64, 0, 103, 52, 19, 77, 41, 93, 28, 66])
print(virat_runs[10:100]) # stop beyond the end is clipped
print(virat_runs[20:30]) # completely outside -> empty array
print(virat_runs[5:2]) # start after stop with positive step -> empty
print(virat_runs[5:2].shape)text
[41 93 28 66]
[]
[]
(0,)How it works: unlike indexing, slicing clips out-of-range bounds silently. If the range is empty you get an empty array with shape (0,) — no error. This is convenient, but it also means a typo can quietly give you nothing.
Index vs slice — the result shape
| Expression | What you get | Shape |
|---|---|---|
virat_runs[3] | one scalar value 31 | () — not an array |
virat_runs[3:4] | an array holding one value [31] | (1,) |
virat_runs[3:7] | an array of 4 values | (4,) |
Note:
arr[3]andarr[3:4]look similar but are different things — a number vs a 1-element array. This matters a lot in 2D: an integer index removes a dimension, a slice keeps it.
Python list vs NumPy (slicing)
| Python list | NumPy array | |
|---|---|---|
| Syntax | lst[start:stop:step] | arr[start:stop:step] — identical |
| Result | a new list (copy) | a view sharing memory |
| Changing the slice | original list unchanged | original array changes too |
| Multi-dimensional | lst[0][1:3] (one level at a time) | arr[0, 1:3] (all axes in one bracket) |
Common mistakes
- ❌ Expecting
virat_runs[2:7]to include index 7. ✅stopis excluded — it returns indexes 2–6. - ❌
virat_runs[-3:-1]for "the last 3". ✅ That gives only 2 values (stop -1 is excluded). Writevirat_runs[-3:]. - ❌
virat_runs[5:2]to go backwards. ✅ Use a negative step:virat_runs[5:2:-1]. - ❌
step = 0→ValueError: slice step cannot be zero. - ❌ Assuming a slice is an independent copy. ✅ It is a view; use
.copy()if you want to change it safely.
Interview tip
Q: How do you reverse a NumPy array without a loop?
A: arr[::-1]. The empty start and stop mean "the whole array" and step = -1 walks backwards. It's a view, so it's O(1) — no data is copied (use np.flip(arr) for the same thing in function form).
Key points to remember
- Slicing syntax is arr[start:stop:step]; start is included, stop is EXCLUDED.
- Omitted values default to start=0, stop=end, step=1 (with a negative step the defaults flip to 'from the end, to the beginning').
- arr[:n] = first n, arr[-n:] = last n, arr[::2] = every other element, arr[::-1] = reversed.
- Number of elements in arr[a:b] (step 1) is b - a.
- Out-of-range slice bounds are clipped silently; an empty range gives an empty array, never an IndexError.
- arr[3] returns a scalar, arr[3:4] returns a 1-element array.
- A NumPy slice is a VIEW of the original data, unlike a Python list slice which is a copy.
Try it yourself
First, last and middle ranges
Step and reverse
Practice: last 5 matches, newest first
Revision Flashcards
Tap a card to flip it and see the answer.
