Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular pairs from array? [duplicate]

Tags:

python

arrays

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?

like image 995
John Avatar asked Feb 13 '17 22:02

John


2 Answers

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)]
like image 120
Eric Duminil Avatar answered Nov 01 '22 17:11

Eric Duminil


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])]
like image 10
Jean-François Fabre Avatar answered Nov 01 '22 18:11

Jean-François Fabre