views:

232

answers:

3

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?

+2  A: 

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.

Mark Byers
And any other custom object which has potentially implemented multi-dimensional slicing via `__getitem__()`.
Amber
A: 

if you try it, you get it:

>>> a = [1,2,3,4,5,6,7,8,9]
>>> sl = slice(2,8,2)
>>> sl
slice(2, 8, 2)
>>> a[sl]
[3, 5, 7]

For the other example you give:

>>> a[2:6,3]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: list indices must be integers, not tuple

it doesnt work in py2.6

joaquin
The "other example" is copied right out of the Python docs. http://docs.python.org/library/functions.html#slice
Josh Wright
it doesn't work in all versions including 3.1
Dingle
It "doesn't work" because you both are assuming that `a` is a list. Slice syntax is used for more than just lists - it's also used for multi-dimensional objects like NumPy arrays.
Amber
+7  A: 

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 extended 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)
unutbu
I see. Basically, a[start:stop, i] only works with multidimensional arrays as implemented in numpy.
Dingle
@Dingle: Or, you can define your own classes with `__getitem__` and assign your own meaning and behavior!
unutbu
The question is similar to http://stackoverflow.com/questions/752602/slicing-in-python-expressions-documentation, but your example and the toy code are much easier to follow.
Dingle