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.
2 comments:
The easiest way is to use the itertools module's cycle function.
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.
Can we do make use of the exception handling ?
Post a Comment