What is `a[start:stop, i]` in Python slicing?

Viewed 171

Python doc for built-in function slice is (emphasis mine):

class slice(stop)
class slice(start, stop[, step])

Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default). They have no other explicit functionality; however they are used by NumPy and other third party packages. Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.

What does a[start:stop, i] mean?

I tried it out (in Python 3.6):

a = [1, 2, 3, 4, 5, 6]
a[1:3,1]

but got:

TypeError: list indices must be integers or slices, not tuple
1 Answers

You cannot combine : and , with lists.

: is for direct slicing:

a[1:3:1]

, is used with slice:

a[slice(1,3,1)]

However with objects supporting it (like numpy arrays) you can slice in several dimensions:

import numpy as np
a = np.array([[0,1,3],[3,4,5]])
a[0:1,2]

output: array([3])

Related