Tuplifying a list or pairs in Python

Problem: You need to convert a list like [ “x”, 1, “y”, 2 ] to [ (“x”, 1), (“y”, 2) ]. This is input from a legacy system. Chiman on python.fi IRC channel come up with a neat solution.

>>> a = [1, 2, 3, 4]
>>> zip(*[a[x::2] for x in (0, 1)])
[(1, 2), (3, 4)]

In readability wise this might not be the optimal solution, so alternative ideas are also welcome 🙂

Also here is a generic solution where you can set the length of a tuple.

Is “tuplyfying” English….?

\"\" Subscribe to RSS feed Follow me on Twitter Follow me on Facebook Follow me Google+

9 thoughts on “Tuplifying a list or pairs in Python

  1. Pingback: Tweets that mention Tuplifying a list or pairs in Python | mFabrik - web and mobile development -- Topsy.com

  2. I’ve always admired this solution:

    >>> a = [1, 2, 3, 4]
    >>> i = iter(a)
    >>> zip(i, i)
    [(1, 2), (3, 4)]

    although if I ever decided to use it, I’d wrap it in a function and thoroughly unit-test it to ensure a change in the implementation of zip() wouldn’t break it without me noticing.

  3. Too verbose, you’ll never get anything done if you waste so many keystrokes:

    >>> a = [1, 2, 3, 4]
    >>> zip(*[iter(a)]*2)
    [(1, 2), (3, 4)]

  4. This example from python documentation uses itertools to achieve the same:

    def grouper(n, iterable, fillvalue=None):
    “grouper(3, ‘ABCDEFG’, ‘x’) –> ABC DEF Gxx”
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

    http://docs.python.org/library/itertools.html#recipes

    Of course it returns an iterator but i’d say this is pretty scalable to large amounts of data.

  5. In real life, the way I’ll prefer to do it is:

    >>> my_list = [1, 2, 3, 4]
    >>> a, b, c, d = my_list
    >>> result = [(a, b), (c, d)]
    >>> result
    [(1, 2), (3, 4)]

    Of course this works only for a fixed number of items.

  6. explicit is good:

    >>> l = [1,2,3,4]
    >>> [(l[2*i], l[2*i+1]) for i in xrange(len(l)/2)]
    [(1, 2), (3, 4)]

    All the other solutions so far (except Daniel’s maybe?) can’t be understood by a Python newbie, and for me that’s enough to discard them. Python is meant to be readable, that’s not Perl 😉

Leave a Reply

Your email address will not be published. Required fields are marked *