-1

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):]

smc
  • 205
  • 2
  • 10
  • 3
    Have you tried `print ('Prev elements are', list[:idx])`? Note the heading `:` not trailing – Chris Oct 23 '19 at 12:09
  • If you want the next elements, why are you subtracting 1? Use `list[idx+1:]` – yatu Oct 23 '19 at 12:10
  • Also, don't call your objects `list` because that tramples the built-in type – roganjosh Oct 23 '19 at 12:11
  • @Chris I never thought about that. Works perfectly.I did a lot of googling still didn't find this. – smc Oct 23 '19 at 12:12
  • 1
    Possible duplicate of [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) – Chris Oct 23 '19 at 12:13
  • 2
    Take a look at the linked answer. It would be a good start for understanding slicing – Chris Oct 23 '19 at 12:14

2 Answers2

4

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 [].

matox
  • 885
  • 11
  • 27
1

The correct expression for the previous elements would be

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

Also, small note, don't name your lists list as list is a reserved name in Python, used as the name of the language-provided list type!

ashiswin
  • 637
  • 5
  • 11
  • Thanks for pointing out that naming error. Actual name is different. While editing and simplifying question I accidentally named it as list. – smc Oct 24 '19 at 09:04