Construct a circular loop in python

6.8k views Asked by At

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]

6

There are 6 answers

1
Aesthete On

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
0
justhalf On

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)
0
lebolo On

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
0
Zimm3r On
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
0
flornquake On

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)
# ...
0
Vladimir Chub On

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)]