# map, filter, reduce, zip, range, and.. slice?

Peter Hansen peter at engcorp.com
Thu Nov 1 02:09:52 CET 2001

```Eyal Lotem wrote:
>
> To get to the point, I've almost always lacked a 'slice' function, that
> slices sequences into smaller chunks.  For example:
>
> divide("Hello world!", 2) => ["He", "ll", "o ", "wo", "rl", "d!"]

How would this do?  Note it can't in general guarantee to return
chunks of equal size, but a simple exception could be used to

>>> def divide(s, n):
...   return map(lambda i, s=s, n=n : s[i:i+n], xrange(0, len(s), n))
...
>>> divide('Hello world!', 2)
['He', 'll', 'o ', 'wo', 'rl', 'd!']
>>> divide('Hello world', 2)
['He', 'll', 'o ', 'wo', 'rl', 'd']
>>> divide('Hello world!, 55)
['Hello world!']
>>> divide('', 2)
[]
>>> divide('Hello world!', 3)
['Hel', 'lo ', 'wor', 'ld!']
>>> divide(hex(-889275714)[2:].upper(), 2)
['CA', 'FE', 'BA', 'BE']
>>> divide([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

Thanks for the inspiration to write this.  I'm pretty sure this is
a method I've needed several times before and never could get my
head wrapped around Python's sophisticated underside enough to
figure it out.

--
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com

```