Converting a flat list to a list of tuples

Fredrik Lundh fredrik at pythonware.com
Tue Nov 22 06:23:08 EST 2005


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

simplest possible (works in all Python versions):

    L = ['a', 1, 'b', 2, 'c', 3]

    out = []
    for i in range(0, len(L), 2):
        out.append(L[i:i+2])

or, on one line (works in all modern versions):

    out = [L[i:i+2] for i in range(0, len(L), 2)]

or, from the slightly-silly-department:

    out = map(list, zip(L[0::2], L[1::2]))

or, using the standard grouping pydiom:

    out = []; item = []
    for i in L:
        item.append(i)
        if len(item) == 2:
            out.append(item)
            item = []
    if item:
        out.append(item)

etc.

</F>






More information about the Python-list mailing list