0

I am trying to do something pretty simple: I need to get the last 40 elements from a list.

I noticed that there is no direct way to do so, like you would do in a string, using one of the standard functions to get the last n chars from the string.

I know how to get the the length of the list; so what I had in mind is to just use the max lenght and do a for loop starting from the end of the list, and go backwards for 80 times.

max_size= len(my_list)

for i in range(max_size, (maxsize-80)):
    print my_list[i]
    i=i-1

Is this the correct way to do so? Or there is some sort of function in the list object that may do this? I tried the documentations of the python site but had no luck.

3 Answers3

2

my_list[-40:] contains the last 40 items. Specifically, a negative list index tells it to start counting that many items back from the end of the list, and the colon afterward tells it to continue until the end.

octern
  • 4,825
  • 21
  • 38
1
for i in my_list[-40:]:
    print(i)
jurgenreza
  • 5,856
  • 2
  • 25
  • 37
0

Slicing is what you want as has been pointed out. You could if you only had an iterable (ie, you don't have a length / can only read forward):

>>> from collections import deque
>>> deque(range(10), 2)
deque([8, 9], maxlen=2)
Jon Clements
  • 138,671
  • 33
  • 247
  • 280