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.
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)]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With