pythonpython-3.xlist

How to pair up consecutive elements in a list, without overlap?


Simple problem: I have u = [1, 2, 3, 4, 5, 6]. I want v = [(1,2), (3,4), (5,6)]. How?

Obviously, one solution is:

v = []
for i in range(len(u)):
    j = 2*i
    v += [(u(j), u(j+1))]

But this is so ugly and lame I hate looking at it every time I do it. Is there a better way?


Solution

  • zip is a pythonic solution.

    list(zip(u[::2], u[1::2]))