Packing list elements into tuples

Russell Blau russblau at hotmail.com
Wed Nov 10 08:53:51 EST 2004


"Nickolay Kolev" <nmkolev at uni-bonn.de> wrote in message
news:cmreif$rve$1 at f1node01.rhrz.uni-bonn.de...
> Nickolay Kolev wrote:
>
> I found it in the cookbook:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303060
>
> It looks quite cryptic, could anyone give me some pointers at what
> exactly is going on in the function?

The function contains only one significant line, which is:

    return zip(*[lst[i::n] for i in range(n)])

To figure out what it is doing, take it one piece at a time.  Start with a
list:

>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Pick how many elements you want in each group:

>>> n=3

Now see what the list comprehension does:

>>> [lst[i::n] for i in range(n)]
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]

So this breaks up the list into three separate lists by taking each n'th
element from the original list, then combines them.  The "n" in lst[i::n]
determines how many elements will be skipped in creating each sub-list.
Unfortunately, this syntax isn't mentioned in the tutorial or the library
reference; you have to dig to find an explanation of it in
http://www.python.org/doc/2.3.4/whatsnew/section-slices.html

Let's store the result of the last step so we can see what the following
step does:

>>> m = [lst[i::n] for i in range(n)]
>>> zip(*m)
[(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12)]

The magic function zip() takes a list of sequences as its argument, and
returns a new list that rearranges them.  Imagine the first list (m) as a
two-dimensional table in which each sub-sequence is a row; zip() goes
through the table and returns the columns as the sub-sequences.  See
http://www.python.org/doc/2.3.4/lib/built-in-funcs.html (all the way at the
end).


-- 
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.






More information about the Python-list mailing list