dingerkingh dingerkingh - 7 months ago 32
Python Question

Previous and next item of list python

Can anyone point me towards a practical way of getting the previous and next items of a list. For example:

my_list = [100, 200, 300, 400]

Is there a practical way of getting the previous and next item (300 and 100).

I am using
my_list[my_list.index(400) - 1]
to successfully get the previous item. Python doesn't mind getting a negative index apparently. However, if I try
my_list[my_list.index(400) + 1]
it doesn't like having an index greater than the number of items in the list. Which makes sense.

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range

I suppose I can use a loop to loop through and get it - I was just hoping there was a simpler solution. I was thinking along the lines of using
but I can't seem to figure out if it is possible to set the index.


A simple solution is to use modulo

my_list[ (my_list.index(400) + 1) % len(my_list) ]


>> 100