Packing list elements into tuples

Steven Bethard steven.bethard at gmail.com
Wed Nov 10 11:49:27 EST 2004


On Wed, 10 Nov 2004 19:00:52 +0800, Deepak Sarda <deepak.sarda at gmail.com> wrote:
>
> > >>> l = [1,2,3,4,5,6]
> > >>> zip(*(iter(l),)*3)
> > [(1, 2, 3), (4, 5, 6)]
> > >>> l = [1,2,3,4,5,6,7,8,9]
> > >>> zip(*(iter(l),)*3)
> > [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
> 
> Can someone explain how this works?!
> 
[snip]
> 
> So zip() basically gets  zip(iter(l), iter(l), iter(l)) , right?

Close, but note that zip(iter(l), iter(l), iter(l)) creates three
iterators to the list l, while zip(*(iter(l),)*3) uses the same
iterator at each position in the tuple.

>>> l = [1,2,3,4,5,6]
>>> zip(iter(l), iter(l), iter(l))
[(1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5), (6, 6, 6)]
>>> itr = iter(l)
>>> zip(itr, itr, itr)
[(1, 2, 3), (4, 5, 6)]

Here's basically what zip ends up doing when you give it 3 names bound
to the same iterator:

>>> itr = iter(l)
>>> tuple1 = (itr.next(), itr.next(), itr.next())
>>> tuple1
(1, 2, 3)
>>> tuple2 = (itr.next(), itr.next(), itr.next())
>>> tuple2
(4, 5, 6)
>>> result = [tuple1, tuple2]
>>> result
[(1, 2, 3), (4, 5, 6)]

Note that when they're not the same iterator, zip does something like:

>>> itr1, itr2, itr3 = iter(l), iter(l), iter(l)
>>> tuple1 = (itr1.next(), itr2.next(), itr3.next())
>>> tuple1
(1, 1, 1)
>>> tuple2 = (itr1.next(), itr2.next(), itr3.next())
>>> tuple2
(2, 2, 2)
...

So you just get 3 copies of the elements at each index in your list.

Hope that helped!

Steve
-- 
You can wordify anything if you just verb it.
        - Bucky Katt, Get Fuzzy



More information about the Python-list mailing list