Getting next element while cycling through a list

li = [0, 1, 2, 3]

running = True
while running:
    for elem in li:
        thiselem = elem
        nextelem = li[li.index(elem)+1]

When this reaches the last element, an IndexError is raised (as is the case for any list, tuple, dictionary, or string that is iterated). I actually want at that point for nextelem to equal li[0]. My rather cumbersome solution to this was

while running:
    for elem in li:
        thiselem = elem
        nextelem = li[li.index(elem)-len(li)+1]   # negative index

Is there a better way of doing this?

cycling through a list of colors with sass

It is possible to have list of three colors: $color-list: x y z; And then apply these three colors by cycling through them and adding them to on an unordered list item. I want: <li>row 1</li

Cycling through the list over and over

List players contains instances of class Players. I want to increase index of list by 1 for each cycle, but after it reaches last element, it should start from 0 again. Basically, it’s a poker code,

“Prev” button not cycling through array, “Next” button works fine

I am trying to get Next and Previous buttons working in my program. The next button works as expected, but I can’t get the logic right for the previous button. I am getting the error: Exception i

Traversing through a linked list: while(ptr!=NULL) vs while(ptr->next!=NULL)?

Defining a memory cell by struct node { int item; node *next; }; and assuming ptr is pointing to a linked list, is there a difference between putting while(ptr!=NULL) vs while(ptr->next!=NULL) to

Excel Macro: cycle through rows, while cycling through sheets

I have a workbook with a few hundred worksheets, each laid out in the same way (i.e. possessing the same columns) though with varying numbers of rows of data. I would like to cycle through each row in

cycling through leds

Please help me with this code, it is making me crazy. This is a very simple program with 8-bit timer, cycling through all 8 leds (one-by-one). Am using ATSTK600 board. My timers are working well, I th

Cycling through a list of list, checking and removing?

Using the following list of lists (4 individual lists inside one big list) myvariable = [[‘test’, ‘xxxx’, ‘DDDt’, ‘EEEst’, ‘2323t’, ‘test’, ‘test’, ‘test’], [‘test’, ‘xxxx’, ‘DDDt’, ‘EEEst’, ‘2323t’,

How to access previous/next element while for looping?

Is there a way to access a list(or tuple, or other iterable)’s next, or previous element while looping through with for loop? l=[1,2,3] for item in l: if item==2: get_previous(l,item)

Access 2007 – cycling through values in a list box VBA?

So i have a list box that populates with different sets of data based on user selections. How can I cycle through any given values that may be in the list box? Is this a For Each statement, or what? P

C++ cycling through operators

I have a sum, for example: x + y I also want to perform subtraction, multiplication and division on the same two variables: x – y x * y x / y what’s the optimum way of cycling through all four opera

Answers

while running:
    for elem,next_elem in zip(li, li[1:]+[li[0]]):
        ...

You can use a pairwise cyclic iterator:

from itertools import izip, cycle, tee

def pairwise(seq):
    a, b = tee(seq)
    next(b)
    return izip(a, b)

for elem, next_elem in pairwise(cycle(li)):
    ...

After thinking this through carefully, I think this is the best way. It lets you step off in the middle easily without using break, which I think is important, and it requires minimal computation, so I think it’s the fastest. It also doesn’t require that li be a list or tuple. It could be any iterator.

from itertools import cycle

li = [0, 1, 2, 3]

running = True
licycle = cycle(li)
# Prime the pump
nextelem = licycle.next()
while running:
    thiselem, nextelem = nextelem, licycle.next()

I’m leaving the other solutions here for posterity.

All of that fancy iterator stuff has its place, but not here. Use the % operator.

li = [0, 1, 2, 3]

running = True
while running:
    for idx, elem in enumerate(li):
        thiselem = elem
        nextelem = li[(idx + 1) % len(li)]

Now, if you intend to infinitely cycle through a list, then just do this:

li = [0, 1, 2, 3]

running = True
idx = 0
while running:
    thiselem = li[idx]
    idx = (idx + 1) % len(li)
    nextelem = li[idx]

I think that’s easier to understand than the other solution involving tee, and probably faster too. If you’re sure the list won’t change size, you can squirrel away a copy of len(li) and use that.

This also lets you easily step off the ferris wheel in the middle instead of having to wait for the bucket to come down to the bottom again. The other solutions (including yours) require you check running in the middle of the for loop and then break.

while running:
    lenli = len(li)
    for i, elem in enumerate(li):
        thiselem = elem
        nextelem = li[(i+1)%lenli]

A rather different way to solve this:

   li = [0,1,2,3]

   for i in range(len(li)):

       if i < len(li)-1:

           # until end is reached
           print 'this', li[i]
           print 'next', li[i+1]

       else:

           # end
           print 'this', li[i]

Use the zip method in Python. This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables

    while running:
        for thiselem,nextelem in zip(li, li[1 : ] + li[ : 1]):
            #Do whatever you want with thiselem and nextelem         
c = [ 1, 2, 3, 4 ]

i = int(raw_input(">"))

if i < 4:
    print i + 1
else:
    print -1
        li = [0, 1, 2, 3]
        for elem in li:
            if (li.index(elem))+1 != len(li):
                thiselem = elem
                nextelem = li[li.index(elem)+1]
                print 'thiselem',thiselem
                print 'nextel',nextelem
            else:
                print 'thiselem',li[li.index(elem)]
                print 'nextel',li[li.index(elem)]