Packing list elements into tuples

Russell Blau russblau at hotmail.com
Tue Nov 9 16:45:06 EST 2004


"Nickolay Kolev" <nmkolev at uni-bonn.de> wrote in message
news:cmrcqq$rv4$1 at f1node01.rhrz.uni-bonn.de...
> Hi all,
>
> 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:
>
> l = [1,2,3,4,5,6,7,8,9]
>
> tups = [(1,2,3), (4,5,6), (7,8,9)]

How's this? :

>>> alist
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> tups = [tuple(alist[i:i+3]) for i in xrange(0, len(alist), 3)]
>>> tups
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]


>
> if i can dictionaries it would be even better:
>
>
> l = [1,2,3,4,5,6]
>
> tups = [
> {'first':1,'second':2,'third':3},
> {'first':4,'second':5,'third':6}
> ]

Well, now that you've been introduced to the concept of list indexes and
list comprehensions, I think that extending it to dictionaries is fairly
simple.


-- 
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