The Confusing Double Colon (::) in NumPy

Melody Xu
2 min readAug 25, 2019

--

Starting from the basic. Indexing/Slicing in NumPy has this formula [start:stop:step]

Example 1: y = [1,2,3,4,5,6]

y[2:6:3]

Output is [3,6]

This means starting from index 2 which is number 3 in the array and goes all the way till index 6, which is number six and skip by 2.

Same logic

Example 2: y[-3::-2] returns [4,2]

This means starting from the 3th element from the end, which is number 4, and counting backwards by 2 (skipping 1) until the beginning of the array is reached.

Skipping backwards

Example3: y[::-1] returns [6,5,4,3,2,1]

y[::-3] returns [6,3]

Now using it in a multi-dimensional array

Below r[::3]goes from the first row and then skip 2 rows. The number here means row number. Since there are only 6 rows, r[::7] and r[::10] only return the first row.

Reshape, however, first making the array ‘flat’ and then the code works as if on a single dimensional array.

The first ‘:’ means by row.

--

--

Melody Xu
Melody Xu

No responses yet