8

The extended indexing syntax is mentioned in python's doc.

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

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.

a[start:stop:step] works as described. But what about the second one? How is it used?

5
  • 2
    So you're asking what 'i' means in "a[start:stop, i]"? Commented May 3, 2010 at 20:33
  • Yes, what is "i" if a is supposed to be a sequence? Commented May 3, 2010 at 20:38
  • a is not necessarily a sequence of one of the default primitive types. Commented May 3, 2010 at 20:41
  • Beats the heck out of me... it raises a TypeError if I try something like foo[3:7, 2] Commented May 3, 2010 at 20:41
  • The documentation gives me the impression that a[start:stop, i] should work just like a[start:stop:step]. But it doesn't. Commented May 3, 2010 at 20:45

2 Answers 2

12

a[start:stop,i] calls the method a.__getitem__((slice(start,stop,None), i)).

This raises a TypeError if a is a list, but it is valid and useful notation if a is a numpy array. In fact, I believe the developers of Numpy asked the developers of Python to extend valid Python slicing notation precisely so that numpy array slicing notation could be implemented more easily.

For example,

import numpy as np
arr=np.arange(12).reshape(4,3)
print(arr)
# [[ 0  1  2]
#  [ 3  4  5]
#  [ 6  7  8]
#  [ 9 10 11]]

1:3 selects rows 1 and 2, and the 2 selects the third column:

print(arr[1:3,2])
# [5 8]

PS. To experiment with what slice is getting sent to __getitem__, you can play around with this toy code:

class Foo(list):
    def __getitem__(self,key):
        return repr(key)

foo=Foo(range(10))
print(foo[1:5,1,2])
# (slice(1, 5, None), 1, 2)
Sign up to request clarification or add additional context in comments.

3 Comments

I see. Basically, a[start:stop, i] only works with multidimensional arrays as implemented in numpy.
@Dingle: Or, you can define your own classes with __getitem__ and assign your own meaning and behavior!
The question is similar to stackoverflow.com/questions/752602/…, but your example and the toy code are much easier to follow.
4

The notation [:,:] is used to slice multidimensional arrays. Python doesn't have any multi-dimensional arrays by default, but the syntax supports it and numpy for example takes advantage of this syntax.

1 Comment

And any other custom object which has potentially implemented multi-dimensional slicing via __getitem__().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.