Indexing and Slicing
Slice Range
A sub-range of a 6-element list copied by an index loop, then extracted with
slice syntax. The trace shows i stepping from start to stop - 1 and
sliced growing one element per iteration.
By hand
Walk indices from start to stop - 1 with range(start, stop) and append
each values[i] to sliced. This makes the copy explicit: each element is
read individually and written into the new list.
naive.py
Replay: real traced execution (multi-file project)
values = [10, 20, 30, 40, 50, 60]
start = 1
stop = 4
sliced = []
for i in range(start, stop):
sliced.append(values[i])
print('RESULT:', sliced)
values ← [10, 20, 30, 40, 50, 60]
1values = [10, 20, 30, 40, 50, 60]2start = 1values this step[10, 20, 30, 40, 50, 60]valuesstart ← 1
1values = [10, 20, 30, 40, 50, 60]2start = 13stop = 4values this step1startstop ← 4
2start = 13stop = 44sliced = []values this step4stopsliced ← []
3stop = 44sliced = []5for i in range(start, stop):values this step[]slicedi ← 1
4sliced = []5for i in range(start, stop):6 sliced.append(values[i])values this step1isliced ← [20]
5for i in range(start, stop):6 sliced.append(values[i])7print('RESULT:', sliced)values this step[] → [20]slicedi ← 2
4sliced = []5for i in range(start, stop):6 sliced.append(values[i])values this step1 → 2isliced ← [20, 30]
5for i in range(start, stop):6 sliced.append(values[i])7print('RESULT:', sliced)values this step[20] → [20, 30]slicedi ← 3
4sliced = []5for i in range(start, stop):6 sliced.append(values[i])values this step2 → 3isliced ← [20, 30, 40]
5for i in range(start, stop):6 sliced.append(values[i])7print('RESULT:', sliced)values this step[20, 30] → [20, 30, 40]slicedfor i in range(start, stop):
4sliced = []5for i in range(start, stop):6 sliced.append(values[i])stdout ← RESULT: [20, 30, 40]
6 sliced.append(values[i])7print('RESULT:', sliced)values this stepRESULT: [20, 30, 40]stdout
With NumPy
a[start:stop] returns a view of elements at indices start through
stop - 1 without an explicit loop. The snapshot shows the sliced array's
shape, dtype, and values.
library.py
import numpy as np
values = [10, 20, 30, 40, 50, 60]
start = 1
stop = 4
a = np.array(values)
sliced = a[start:stop]
print('shape:', sliced.shape)
print('dtype:', sliced.dtype)
print('values:', sliced.tolist())
print('RESULT:', sliced.tolist())
shape: (3,)
dtype: int64
values: [20, 30, 40]
RESULT: [20, 30, 40]
Implementation notes
- A NumPy slice returns a view into the original buffer — no copy is made.
Modifying
sliced[0]also modifiesa[start]. Call.copy()on the slice to get an independent array. - Python list slicing (
values[1:4]) always produces a copy. The "By hand" loop makes this copy explicit element-by-element. - Shape, dtype, and values are shown explicitly here because
ndarray.__repr__output varies with NumPy version and print options.