li = [0, 1, 2, 3]
running = True
while running:
for elem in li:
thiselem = elem
nextelem = li[li.index(elem)+1]
When this reac
while running:
lenli = len(li)
for i, elem in enumerate(li):
thiselem = elem
nextelem = li[(i+1)%lenli] # This line is vital
As simple as this:
li = [0, 1, 2, 3]
while 1:
for i, item in enumerate(x):
k = i + 1 if i != len(x) - 1 else 0
print('Current index {} : {}'.format(i,li[k]))
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]
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)]
while running:
lenli = len(li)
for i, elem in enumerate(li):
thiselem = elem
nextelem = li[(i+1)%lenli]
The simple solution is to remove IndexError by incorporating the condition:
if(index<(len(li)-1))
The error 'index out of range' will not occur now as the last index will not be reached. The idea is to access the next element while iterating. On reaching the penultimate element, you can access the last element.
Use enumerate method to add index or counter to an iterable(list, tuple, etc.). Now using the index+1, we can access the next element while iterating through the list.
li = [0, 1, 2, 3]
running = True
while running:
for index, elem in enumerate(li):
if(index<(len(li)-1)):
thiselem = elem
nextelem = li[index+1]