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+
Pingback: Tweets that mention Tuplifying a list or pairs in Python | mFabrik - web and mobile development -- Topsy.com
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.
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)]
Wow Marius, that’s a nice one.
>>> a = [1, 2, 3, 4]
>>> zip(a[0::2], a[1::2])
[(1, 2), (3, 4)]
>>> a=[1,2,3,4]
>>> zip(a[::2], a[1::2])
[(1, 2), (3, 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.
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.
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 😉