Friday, April 01, 2011

Python slice notation

Addressing subsets of a list is easy a hell in Python. Dig this:

Assuming we have a list a=[some items],

a[:]
gives you the entire list. Ok, the benefit of that one maybe wasn't too obvious. Bear with me though!

a[x:y]
gives you items x to y (excluding 'y')

a[x:]
gives you items from x to the end of the list

a[:y]
gives you items from the beginning of the list to (but again excluding) y

So far so good. Let's step it up a notch:

a[x:y:z]
gives you items x to y, hitting only every z item (this is called 'stride')

a[x::z]
gives you items x to the end, with stride z

a[:y:z]
you guessed it: this gives you items from the beginning to y, with stride z

Ok. That about covers it, right? Not quite...

a[-x]
gives you x:th to last item, e.g. a[-1] gives you the last item, a[-2] the second to last and so on.

a[-x:-y]

gives you x:th to last to y:th to last items, so e.g. a[-5:-2] gives you the fifth item to the end to the second item to the end.

Now you probably go: what about a[-2:-5]? That just returns []! That's because not providing a stride means you're implicitly using a stride of +1, which in this case is equal to saying "take two steps back, then walk straight forward one step at a time until you're five steps behind where you started". Now, assuming you walk *straight* forward and don't follow the curvature of the earth, that's one hopeless journey, one which Python fortunately saves you from by just returning [].

Instead try this:

a[-x:-y:-z] 

which much as you'd expect returns the elements a[-x] to a[-y] in reverse order with stride z.

This obviously also means that a[::-1]  gives you the entire list, reversed.

Much like a[::2]  gives you every other item in the list, and a[::-2] gives you every other item in the list, in reverse order.

I may be preaching to the choir here but the ability to leverage Matlab-like short-hand like this inside a modern, object oriented, modular language is one of the things that make Python such an invaluable tool during prototyping and rapid application development, especially in a such a crazy environment as a Hollywood movie production.

Finally, if you agree that the above seems pretty friggin convenient, consider this: 3**9

2 comments:

  1. Anonymous2:08 AM

    Thanks a lot. It is really useful. How did you get to know all this?

    ReplyDelete
  2. Thank you very much

    ReplyDelete