-1

I have a list like this : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and I want to extract the previous 'n' elements from a particular index.

For eg: If I take index 7, I have the element 8 in it. And for n = 3, I want to get the previous 3 elements starting backwards from index 7. The result would be [5, 6, 7].

I am not able to come up with a slicing formula to get this. Could someone please help me?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
AnonymousMe
  • 509
  • 1
  • 5
  • 18

1 Answers1

2

The code is very straight forward:

l = [i for i in range(1,15)]
n = 3
index = 7
print(l[index-n:index])

The Output:

[5, 6, 7]
Ash
  • 375
  • 1
  • 3
  • 14