3

Say we have a list L = [1,2,3,4,5]. Is there a clean way to make a list of tuples of the following form: T = [(1,2),(2,3),(3,4),(4,5)]?

It would be great if there were a nicer alternative to

    T = []
    for i in range(len(L) - 1):
        T.append((L[i], L[i+1]))

Or the equivalent comprehension.

Bach
  • 6,145
  • 7
  • 36
  • 61
rookie
  • 2,783
  • 5
  • 29
  • 43

4 Answers4

11

You can use the inbuilt zip function: zip(L, L[1:])

In [4]: L = [1,2,3,4,5]

In [5]: zip(L, L[1:])
Out[5]: [(1, 2), (2, 3), (3, 4), (4, 5)]
musically_ut
  • 34,028
  • 8
  • 94
  • 106
2

try:

list(zip(l[:-1], l[1:]))

This should do it.

note that

list(zip(l, l[1:]))

works as well, since zip cuts the longest guy, but its less explicit.

Retozi
  • 7,521
  • 1
  • 23
  • 16
  • I find the second to be clearer and would never think of writing the first, even though it is equivalent. The question mentions "T = [(1,2),(2,3),(3,4),(4,5)]" and visial inspection for me shows the first element o each tuple being l; the second being from l[1:]. – Paddy3118 Apr 11 '14 at 07:50
  • well there are always two ways for looking at it, if you are not familiar with the zip function, the first one is in my opinion clearer, because the last element is missing in the first column. You need to know about the cut of zip (there is zip_longest also) – Retozi Apr 11 '14 at 07:57
  • Oh, I know about zip. (I wrote this blog entry on one aspect of it: http://paddy3118.blogspot.co.uk/2007/02/unzip-un-needed-in-python.html). I just wanted to know what aspect of the description made you think your first answer better. You explain that this is due to consideration of the last elements. Equally valid. I guess this is a case of is it a vase or two faces looking at each other: http://en.wikipedia.org/wiki/Rubin_vase – Paddy3118 Apr 11 '14 at 08:05
0
In [15]: L = [1,2,3,4,5]
In [16]: oL = [(x, y) for x, y in zip(L, L[1:])]
In [17]: oL
Out[17]: [(1, 2), (2, 3), (3, 4), (4, 5)]

Or simply

oL = zip(L, L[1:])
shaktimaan
  • 11,962
  • 2
  • 29
  • 33
0

A naive approach using list comprehension, this would work as well, though I am not sure if using zip is faster.

L = [1,2,3,4,5]
[(L[i], L[i+1]) for i in range(len(L) - 1)]
ajay
  • 9,402
  • 8
  • 44
  • 71