Table of Contents#### Download Safari Books Online apps: Apple iOS | Android | BlackBerry

## 19.6. Dividing an Iterable into n Slices of Stride n

### Problem

### Solution

Entire Site

Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

*Credit: Gyro Funch, Alex Martelli*

You have an iterable * p* and need to
get the

`n`

`n`

`p`

`[`

`0`

`:`

:`n`

`]`

, `p`

`[1:`

:`n`

`]`

, and so on up to
`p`

`[`

`n`

`-1:`

:`n`

`]`

.While extended slicing would return sequences of the same type
we start with, it’s much more sensible to specify a `strider`

function that, instead, solves this
problem by returning a list of lists:

def strider(p, n): """ Split an iterable p into a list of n sublists, repeatedly taking the next element of p and adding it to the next sublist. Example: >>> strider('abcde', 3) [['a', 'd'], ['b', 'e'], ['c']] In other words, strider's result is equal to: [list(p[i::n]) for i in xrange(n)] if iterable p is a sequence supporting extended-slicing syntax. """ # First, prepare the result, a list of n separate lists result = [ [ ] for x in xrange(n) ] # Loop over the input, appending each item to one of # result's lists, in "round robin" fashion for i, item in enumerate(p): result[i % n].append(item) return result