I have a list of python objects:
fruits = [ 'apple', 'orange', 'banana', 'grape', 'cherry' ]
I currently have a for
loop in a class method that returns "prev_fruit" and "next_fruit" objects for a given object:
def get_prev_next(self, fruit_list):
prev_fruit = next_fruit = None
fruit_list_length = len(fruit_list)
for idx, fruit in enumerate(fruit_list):
if fruit == self:
if idx > 0:
prev_fruit = fruit_list[idx-1]
if idx < (fruit_list_length-1):
next_fruit = fruit_list[idx+1]
return prev_fruit, next_fruit
This works although there are probably more efficient ways of doing it (which I'm happy to learn about).
I now want the list to optionally be "looping" (previous for first index is last and next index for last is first).
def get_prev_next(self, fruit_list, looping=False):
...
What is an efficient way to do this on lists of objects with 1-10000 values?
"efficient" is necessarily not "most efficient" as code legibility and portability is a factor - I don't want to relearn the approach six months from now