Slices and dices

31.08.2010 19:33

Somehow this little corner of Python successfully evaded my discovery until now. Did you know there's a slice object that describes how an array is sliced? It can be passed in most places where a start:stop construct would go.

For instance:

>>> b = range(10)
>>> b[2:4]
[2, 3]
>>> a = slice(2,4)
>>> b[a]
[2, 3]

But more importantly, also:

>>> from operator import itemgetter
>>> f = itemgetter(slice(2,4))
>>> f(range(10))
[2, 3]

Which somewhat expands the usefulness of itemgetter in combination with itertools functions for efficient inner loops.

Interestingly, start:stop doesn't actually construct a slice object, so this:

>>> a = 2:4

is a syntax error. Funny. As far as I know this is the only place where Python's everything-is-an-object philosophy breaks. I would expect this to create an object just like a comma transparently generates a tuple.

Posted by Tomaž | Categories: Code

Comments

I wouldn't say it breaks the everything-is-an-object philosophy, there's just no syntax for slices (apart from slice(a, b)). It's like with sets: There used to be no syntax apart from set([1, 2, 3]). Only since very recently you can also say {1, 2, 3}.

Well, my point is that obviously there is a short-hand syntax for slices - "n:m" - but it's inconsistent. If a[2:4] is equivalent to a[slice(2,4)], why isn't then b = slice(2,4) equivalent to b = 2:4? It's like the range() function would be restricted to the use inside a for-loop.

I understand there are probably good reasons why the colon syntax is limited to use inside brackets. Perhaps parser complexity or performance. I'm just saying it feels a little weird for Python.

Posted by Tomaž

Add a new comment


(No HTML tags allowed. Separate paragraphs with a blank line.)