tadhg.com
tadhg.com
 

Python Extended List Slicing

23:18 Thu 01 Oct 2009. Updated: 08:20 02 Oct 2009
[, ]

I never knew about this optional third parameter to list slices—in addition to e.g. getting the third to fifth items in a list with somelist[2:5], you can also get every nth item with somelist[::n].

This makes it very easy to get every odd or even item in a list, odd with somelist[::2] and even with somelist[1::2].

Where I think this is particularly handy is if you have to grab e.g. three-line chunks out of some text:

chunks = []
lines = text.split("\n")
for i in range(0, len(lines))[::3]:
    chunk = []
    chunk.append(lines[i])
    chunk.append(lines[i+1])
    chunk.append(lines[i+2])
    chunks.append("\n".join(chunk))

The docs on extended slices are here.

One Response to “Python Extended List Slicing”

  1. lena Says:

    When i clicked on the headline i thought i was going to see some pythons sliced into pieces! How stupid! LOL.

Leave a Reply