Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pairwise circular Python 'for' loop

Tags:

python

Is there a nice Pythonic way to loop over a list, retuning a pair of elements? The last element should be paired with the first.

So for instance, if I have the list [1, 2, 3], I would like to get the following pairs:

  • 1 - 2
  • 2 - 3
  • 3 - 1
like image 637
The Oddler Avatar asked Apr 28 '16 14:04

The Oddler


2 Answers

A Pythonic way to access a list pairwise is: zip(L, L[1:]). To connect the last item to the first one:

>>> L = [1, 2, 3] >>> zip(L, L[1:] + L[:1]) [(1, 2), (2, 3), (3, 1)] 
like image 129
jfs Avatar answered Sep 17 '22 23:09

jfs


I would use a deque with zip to achieve this.

>>> from collections import deque >>> >>> l = [1,2,3] >>> d = deque(l) >>> d.rotate(-1) >>> zip(l, d) [(1, 2), (2, 3), (3, 1)] 
like image 23
g.d.d.c Avatar answered Sep 17 '22 23:09

g.d.d.c