-4

I have a list of unknown length which I want to get the 5th to last, 4th to last, and 3rd to last elements from:

So if my list is like. a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I want to get. b = [6, 7, 8]

I can get this with b = a[6:9]

But the issue is my list could contain any number of items, so it could be.

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

and in this case b should be [9, 10, 11] which b = a[6:9] does not give.

How can I always get the 5th to last third last items in a list, my list will always be over 5 elements long.

Ma0
  • 15,057
  • 4
  • 35
  • 65

2 Answers2

3

You can use negative indexing with list slices, so b = a[-5:-2] will always return your desired list regardless of your original lists size.

Example 1:

>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> b = a[-5:-2]
>>> b
[6, 7, 8]

Example 2:

>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
>>> b = a[-5:-2]
>>> b
[9, 10, 11]
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
1

You can use negative indexing. a[-1] indicates your last element,a[-2] indicates your second last element and so on. Suppose you want to get last 5 elements. The you can write :

my_list = a[-5:]

Also follow shash678's answer. You can read What is negative index in Python?

Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39