0

I want to loop a list over a cycle. ex: I have three elements in the array L = [1,2,3] I want to get the output as

L[0],L[1]

L[1],L[2]

L[2],L[0]

Is there a easy way get the slightly different output

L[0],L[1]

L[1],L[2]

L[0],L[2]

  • Reverse duped only because the other post has better answers. If there is a dispute, please ping me here or in the [Python](http://chat.stackoverflow.com/rooms/6/python) chatroom – Bhargav Rao May 01 '16 at 15:25

6 Answers6

3

Using modulus operator

>>> a = [1,2,3]
>>> for x in range(10):
        print a[x % len(a)]

Using itertools.cycle

>>> iterator = cycle(a)
>>> for _ in range(10):
        print next(iterator)

As for your output, you could just do this.

>>> for x in range(10):
        print '{0}, {1}'.format(a[x % len(a)], a[(x+1) % len(a)])

>>> 1, 2
>>> 2, 3
>>> 3, 1
... etc etc
Aesthete
  • 18,622
  • 6
  • 36
  • 45
  • The `itertools.cycle` is pretty interesting! Although from the [docs](http://docs.python.org/2/library/itertools.html#itertools.cycle): "Note, this member of the toolkit may require significant auxiliary storage (depending on the length of the iterable)." – lebolo Sep 06 '13 at 02:26
1

You can just use increasing index, and use modulo (remainder of division)

myList = [1,2,3]
for i in xrange(len(myList)):
    myTuple = (myList[i],myList[(i+1)%len(myList)])
    print myTuple

will produce:

(1,2)
(2,3)
(3,1)
justhalf
  • 8,960
  • 3
  • 47
  • 74
1

You could try something like

L = [1,2,3]
length = len(L)
for i in xrange(length):
        print L[i % length], L[(i+1) % length]

Output

1 2
2 3
3 1

This way, you can do something like xrange(10) and still have it cycle:

1 2
2 3
3 1
1 2
2 3
3 1
1 2
2 3
3 1
1 2
lebolo
  • 2,120
  • 4
  • 29
  • 44
1
l = [0,1,2,3]
for i in xrange(0, len(l)):
    print l[i], l[(i+1) % len(l)]


0 1
1 2
2 3
3 0
Zimm3r
  • 3,369
  • 5
  • 35
  • 53
0

There is a recipe in the itertools documentation that you can use:

import itertools
def pairwise(iterable):
    a, b = itertools.tee(iterable)
    next(b, None)
    return itertools.izip(a, b)

Call this with itertools.cycle(L) and you're good to go:

L = [1, 2, 3]
for pair in pairwise(itertools.cycle(L)):
    print pair
# (1, 2)
# (2, 3)
# (3, 1)
# (1, 2)
# ...
flornquake
  • 3,156
  • 1
  • 21
  • 32
0

Did you mean combinations? http://en.wikipedia.org/wiki/Combination

from itertools import combinations
comb = []
for c in combinations([1, 2, 3], 2):
    print comb.append(c)

For sorting you can use then

sorted(comb, key=lambda x: x[1])

Output:

[(1, 2), (1, 3), (2, 3)]
Vladimir Chub
  • 461
  • 6
  • 19