Search code examples
pythonlistelementitems

Best way to find previous and next elements in a list


What is the efficient way to find the previous and next elements based on a given element index?

list = [(100, 112), (100, 100), (200, 100), (200, 125), (240, 130), (240, 100), (272, 100)]
idx = 2 # for example
print('Next elements are', list[idx + 1:] )

Correct output

Next elements are [(200, 125), (240, 130), (240, 100), (272, 100)]

while this line prints wrong elements:

print ('Prev elements are', list[idx - 1:])

Wrong output

[(100, 100), (200, 100), (200, 125), (240, 130), (240, 100), (272, 100)]

Why this is happening? I tried this too list[(idx-1)%len(list):]


Solution

  • If you have array like this:

    arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    and index defined:

    index = 4
    

    Elements before:

    print(arr[:index])
    > [0, 1, 2, 3]
    

    Elements after:

    print(arr[index+1:])
    > [5, 6, 7, 8, 9]
    

    PS: If your index is in range(0, len(arr)-2) then you are going to get after elements, otherwise you will get [].