I can't believe this is nowhere to be found, but: I want all consecutive pairs from an array, including the last element with the first one. I tried:
[(a, b) for a, b in zip(list, list[1:])]
What is the most pythonic and efficient way to do it?
Another approach would be to use modulo to jump back from the last element to the first one :
l = [1,2,3,4,5,6]
n = len(l)
[(l[i], l[(i+1) % n]) for i in range(n)]
It returns :
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 1)]
you just have to add the first element to the second list:
l = [1,2,3,4,5,6]
r = [(a, b) for a, b in zip(l, l[1:]+l[:1])]
result:
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 1)]
Aside: "pythonic" also means not using list
as a variable name.
Variant: use itertools.ziplongest
instead of zip
and fill with first element (as a bonus, also works with numpy
arrays since no addition):
import itertools
r = [(a, b) for a, b in itertools.zip_longest(l, l[1:], fillvalue=l[0])]
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