Converting a flat list to a list of tuples

Steven D'Aprano steve at REMOVETHIScyber.com.au
Tue Nov 22 06:18:06 EST 2005


On Tue, 22 Nov 2005 02:57:14 -0800, metiu uitem wrote:

> Say you have a flat list:
> ['a', 1, 'b', 2, 'c', 3]
> 
> How do you efficiently get
> [['a', 1], ['b', 2], ['c', 3]]

def split_and_combine(L):
    newL = []
    for i in range(len(L)//2):
        newL.append( [L[2*i], L[2*i+1]] )
    return newL

Another possibility is a list comprehension:

L = ['a', 1, 'b', 2, 'c', 3] 
[[L[i], L[i+1]] for i in range(len(L)) if i%2 == 0]

Personally, I think that's just about as complex as a single list
comprehension should get. Otherwise it is too easy to create
unmaintainable code.

It is much easier (and probably faster) if you arrange matters so that you
have two lists at the start:

zip( ['a', 'b', 'c'], [1, 2, 3] )

returns [('a', 1), ('b', 2), ('c', 3)]

If you absolutely need the inner tuples to be lists, use a list
comprehension afterwards:

[list(t) for t in zip(['a', 'b', 'c'], [1, 2, 3])]


-- 
Steven.




More information about the Python-list mailing list