Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting next element while cycling through a list

People also ask

How do you get the next element while cycling through a list in Python?

Get Next Element in Python List using next() First of all, convert the list into the iterative cycle using cycle() method. For that, you have to import the cycle from itertools which come preinstalled with Python. Then use the next() method to find the next element in the Python iterator.

How do you get the next element in a for loop?

Use enumerate() function to access the next item in a list in python for a loop. The for loop allows to access the variables next to the current value of the indexing variable in the list.

How do you get the next value in Python?

Python next() FunctionThe next() function returns the next item in an iterator. You can add a default return value, to return if the iterable has reached to its end.


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 = next(licycle)
while running:
    thiselem, nextelem = nextelem, next(licycle)

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:
    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)):
    ...

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

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         

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]