Python - How to extract the last x elements from a list [duplicate]

If the length of a python list is greater than a given value (say 10), then I want to extract the last 10 elements in that list into a new list. How can I do this? I tried getting the difference between len(my_list) - 10 and use it as: new_list = [(len(my_list) - 10):] which does not work

Any suggestions? Thanks in advance


it's just as simple as:

my_list[-10:]

Additional Comment: (from the comments section)

If the initial list is less than 10 elements, then this solution will still work yielding the whole list. E.g. if my_list = [1,2,3], then my_list[-10:] is equal to [1,2,3]


This shows how to chop a long list into a maximum size and put the rest in a new list. It's not exactly what you're asking about, but it may be what you really want:

>>> list1 = [10, 20, 30, 40, 50, 60, 70]
>>> max_size = 5
>>> list2 = list1[max_size:]
>>> list2
[60, 70]
>>> list1 = list1[:max_size]
>>> list1
[10, 20, 30, 40, 50]

This is more like what you're asking about, basically the same, but taking the new list from the end:

>>> list1 = [10, 20, 30, 40, 50, 60, 70]
>>> list2 = list1[:max_size]
>>> list2
[10, 20, 30, 40, 50]
>>> list2 = list1[-max_size:]
>>> list2
[30, 40, 50, 60, 70]
>>> list1 = list1[:-max_size]
>>> list1
[10, 20]
>>> 

The Python tutorial has a section how to use list slicing: http://docs.python.org/tutorial/introduction.html#lists

In your case, it is as simple as writing:

 new_list = my_list[-10:]

Actually, the subscript in the statement of your question works perfectly — could you paste in exactly what error or unexpected result you are seeing when you try using it yourself? Here is a successful run of the subscript you suggest:

>>> my_list = list('abcdefghijklmnop')
>>> new_list = my_list[(len(my_list) - 10):]
>>> new_list
['g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']

Is the problem simply that you forgot to name my_list in front of your slice notation?

Edit: As Felix notes, you should prevent the index from going negative:

my_list[max(0, len(my_list) - 10):]

And, of course, as the other answers note, a constant negative index is actually the easiest way to accomplish your goal; but I wanted to first focus on why your “own way” of getting the last ten elements — which made sense, even if it did not take full advantage of Python's conventions regarding slices — was giving you an error instead.