Get next element from a list in Python
Sometimes you will need to keep some items in the list and get the next item. It can be done easily using a variable as the current position tracker. Check the code below:
You can also do this using an iterator. Try this python code:
This is because the iterator is not circular. It can be fixed like this:
But I was wondering whether there is any straight-forward method to make the iterator circular.
current_position = 0
my_li = [1, 2, 3, 4, 5]
for i in range(0, 8):
value = my_li[current_position % (len(my_li))]
current_position += 1
print value
for i in range(0, 5):
value = my_li[current_position % (len(my_li))]
current_position += 1
print value
You can also do this using an iterator. Try this python code:
def get_next_element(my_itr):
try:
return my_itr.next()
except StopIteration:
return None
my_li = [1, 2, 3, 4, 5]
#convert the list to an iterator
my_itr = iter(my_li)
for i in range(0, 10):
print get_next_element(my_itr)
If you run the code you will see the following output:
1
2
3
4
5
None
None
None
None
None
This is because the iterator is not circular. It can be fixed like this:
def get_next_element(my_itr):
try:
return my_itr.next()
except StopIteration:
return None
my_li = [1, 2, 3, 4, 5]
#convert the list to an iterator
my_itr = iter(my_li)
for i in range(0, 8):
value = get_next_element(my_itr)
if value is None:
my_itr = iter(my_li)
value = get_next_element(my_itr)
print value
But I was wondering whether there is any straight-forward method to make the iterator circular.
Comments
for x itertools.cycle([1,2,3]):
print x
1
2
3
1
2
3
1
2
3
This will go on forever, so there needs to be some way to break the loop.
my_iter = chain(my_li, my_li)
for x in my_iter: print x