Packing list elements into tuples

Peter Otten __peter__ at web.de
Wed Nov 10 04:05:14 EST 2004


Nickolay Kolev wrote:

> I have a list whose length is a multiple of 3. I want to get a list  of
> tuples each of which has 3 consecutive elements from the original list,
> thus packing the list into smaller packets. Like this:

> ... dictionaries ... would be even better:

> l = [1,2,3,4,5,6]
> 
> tups = [
> {'first':1,'second':2,'third':3},
> {'first':4,'second':5,'third':6}
> ]

itertools to the rescue:

>>> from itertools import *
>>> names = "first second third".split()
>>> items = range(6)
>>> map(dict, takewhile(bool, starmap(zip, repeat((names, iter(items))))))
[{'second': 1, 'third': 2, 'first': 0}, {'second': 4, 'third': 5, 'first':
3}]

Fun, but not recommended. There must be a simpler expression where you need
not mention len(names) explicitly - but right now I can't think of one.
Note how the nonzero len(items) % len(names) case is handled:

>>> map(dict, takewhile(bool, starmap(zip, repeat((names,
iter(range(5)))))))
[{'second': 1, 'third': 2, 'first': 0}, {'second': 4, 'first': 3}]

However, in real life I would rather go with Steven Bethard's two-step
approach...

Peter







More information about the Python-list mailing list