[Tutor] a code question, but don't know question's name

Kent Johnson kent37 at tds.net
Sun Oct 7 19:01:45 CEST 2007

Alan Gauld wrote:
> "Kent Johnson" <kent37 at tds.net> wrote
>>> The notation data[;,0] doesn't make sense and is an error in 
>>> Python.
>> [:,0] is an extended slice, not an error:
>> http://docs.python.org/ref/slicings.html
> Really? I got an error from the interpreter.
>>>> d[:,0]
> Traceback (most recent call last):
>   File "<input>", line 1, in ?
> TypeError: list indices must be integers

Ok. What I meant is, it is not a *syntax* error.

> Following the link I get the somewhat obscure explanation:
> """
> The semantics for an extended slicing are as follows.
> The primary must evaluate to a mapping object,
> """
> This bit I understand :-)
> """
> and it is indexed with a key that is constructed from the slice list,
>  as follows. If the slice list contains at least one comma, the key
>  is a tuple containing the conversion of the slice items;
> """
> This seems to be the case here, but where is the tuple?

The tuple is the parameter passed to __getitem__():
In [1]: class sliced(object):
    ...:     def __getitem__(self, item):
    ...:         print repr(item)
In [2]: s=sliced()
In [3]: s[3]
In [4]: s[1:2:3]
slice(1, 2, 3)
In [5]: s[:,0]
(slice(None, None, None), 0)

> If i try testing anything I just get an error.

There's the rub. Extended slicing is not supported by any built-in
containers. That's why you get a TypeError when you try it with a list.

> When were these introduced? I am on v2.4.3

At least since 2.0 :-)
> """
> otherwise, the conversion of the lone slice item is the key. The 
> conversion of a slice item that is an expression is that expression. 
> The conversion of an ellipsis slice item is the built-in Ellipsis 
> object. The conversion of a proper slice is a slice object (see 
> section 3.2) whose start, stop and step attributes are the values of 
> the expressions given as lower bound, upper bound and stride, 
> respectively, substituting None for missing expressions.
> """
> And most of that I don't understand.

It is saying what the values passed to __getitem__() are: either a plain 
object (probably an integer); an Ellipsis object, if the parameter is ...:
In [6]: s[...]

or a slice object, or a tuple of such things.

> Can someone who does give some examples of this
> and what you would use it for?
>> It is used in Numeric/numpy to select from multidimensional arrays.

See the numpy docs for examples.

> I don't use either, but since its part of the languyage I assiume it
> can be used in normal Python lists too?

No. It can be used for user-defined classes but it is not supported by 
any built-ins. IIUC this feature was added specifically for Numeric.


More information about the Tutor mailing list