-1

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 iter() but I can't seem to figure out if it is possible to set the index.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
dingerkingh
  • 448
  • 1
  • 6
  • 16

4 Answers4

5

You could use the modolu operator to "loop" around the list's borders:

>>> my_list = [100, 200, 300, 400]
>>> val = 400
>>> my_list[(my_list.index(val) + 1) % len(my_list)] # next
100
>>> my_list[(my_list.index(val) - 1) % len(my_list)] # previous
300
Mureinik
  • 297,002
  • 52
  • 306
  • 350
5

A simple solution is to use modulo

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

result:

>> 100
YOBA
  • 2,759
  • 1
  • 14
  • 29
0

I suppose that, when you look for the next element "after" 400; you want to get the first one? In that case; just check for the size of your list:

current_index = my_list.index(400)
next_index = current_index + 1
if (next_index == len(my_list)):
    next_index = 0

next_value = my_list[next_index]
Chris Maes
  • 35,025
  • 12
  • 111
  • 136
0

You can use operator %

def get_loop_item(my_list, item, spacing):
    if isinstance(spacing, int):
        return my_list[(my_list.index(item) + spacing) % len(my_list)]
    elif isinstance(spacing, list):
        return [get_loop_item(my_list, item, space) for space in spacing] 
    return None

Test

>>> get_loop_item(my_list, 300, 1)
400
>>> get_loop_item(my_list, 300, -1)
200
>>> get_loop_item(my_list, 300, [-1, 1])
[200, 400]
qvpham
  • 1,896
  • 9
  • 17