Posts

Showing posts from March, 2012

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: 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 li