3

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
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
joseville
  • 685
  • 3
  • 16

1 Answers1

2

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])

mozway
  • 194,879
  • 13
  • 39
  • 75
  • 5
    You can, `a[1:2, 3]` is shorthand for`a.__getitem__((slice(1, 2, None), 3))`, which other classes may support (look at numpy for lots of examples). `list` just can't handle that. – mata Dec 03 '21 at 13:04
  • 1
    @mata I thought the question was for lists, I'll update – mozway Dec 03 '21 at 13:05
  • 1
    Did you see that `a[start:stop, i]` is straight from the Python docs as cites by the OP? – jochen Dec 03 '21 at 13:06