sudheer nalubolu sudheer nalubolu - 1 year ago 67
Python Question

Understanding python slicings syntax as described in the python language reference

The following is the slicings syntax that I copied from The Python Language Reference:

slicing ::= primary "[" slice_list "]"
slice_list ::= slice_item ("," slice_item)* [","]
slice_item ::= expression | proper_slice
proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]
lower_bound ::= expression
upper_bound ::= expression
stride ::= expression

Per my understanding, this syntax equates to
SomeMappingObj[slice_item,slice_item etc...]
which again equates to something like
a =[i for i in range(20)]

But, I can't test this in IPython and I did not find any questions about multiple slicings. Is my interpretation about multiple slicing in python correct? What am I doing incorrectly?

In [442]: a=[i for i in range(20)]

In [443]: a[0:12:2]
Out[443]: [0, 2, 4, 6, 8, 10]

In [444]: a[0:12:2,14:17:1]
TypeError Traceback (most recent call last)
<ipython-input-444-117395d33bfd> in <module>()
----> 1 a[0:12:2,14:17:1]

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

Answer Source

A slice_list should contain as many "dimensions" as the object being indexed. The multi-dimensional capability is not used by any Python library object that I am aware of, but you can test it easily with numpy:

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

There are a number of such features in the Python language that are not used directly in the main library. The __matmul__ magic method (@ operator) is another example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download