Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create (L[i], L[i+1]) tuple list from list L [duplicate]

Tags:

python

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.

like image 647
rookie Avatar asked Dec 02 '25 01:12

rookie


2 Answers

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)]
like image 67
musically_ut Avatar answered Dec 03 '25 15:12

musically_ut


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.

like image 32
Retozi Avatar answered Dec 03 '25 15:12

Retozi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!