79

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

sura
  • 1,471
  • 4
  • 17
  • 25

4 Answers4

144

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]

ihightower
  • 3,093
  • 6
  • 34
  • 49
Felix Yan
  • 14,841
  • 7
  • 48
  • 61
  • 31
    It is still important to mention that 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]`. – ovgolovin Dec 19 '11 at 01:14
24

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]
>>> 
dkamins
  • 21,450
  • 7
  • 55
  • 59
  • There were two good answers already, this does not add much. Sorry for the down vote. – Benjamin Dec 19 '11 at 01:08
  • 13
    @Benjamin: Putting aside the facts that a) an actual interactive example can be very helpful and b) I started answering this before seeing the other answers, you have totally failed to understand the purpose of downvoting on Stack Overflow. Congratulations and have a great day! – dkamins Dec 19 '11 at 01:11
  • 2
    @Benjamin: P.S. for future reference: "When should I vote down? Use your downvotes whenever you encounter an egregiously sloppy, no-effort-expended post, or an answer that is clearly and perhaps dangerously incorrect." ( http://stackoverflow.com/privileges/vote-down ) – dkamins Dec 19 '11 at 01:14
  • 1
    For future reference: People use down votes for different reasons, mine being stated above. If the answer is sound, my down vote will be countered by up votes – Benjamin Dec 19 '11 at 01:21
  • 2
    Maybe there is some badge for downvoting, so Benjamin did that. :) @dkamins Don't worry much about that. He got -1 to rep for minus vote (apart from your -2). – ovgolovin Dec 19 '11 at 01:33
16

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:]
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
6

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.

Brandon Rhodes
  • 83,755
  • 16
  • 106
  • 147
  • 4
    When his list's length is < 10. – Felix Yan Dec 19 '11 at 01:08
  • ooooh, u are correct. I have just forgotten my_list :( – sura Dec 19 '11 at 01:26
  • @FelixYan — you are right, I will fix that! – Brandon Rhodes Dec 19 '11 at 01:40
  • There is no need to guard against negative slice boundaries. –  Dec 19 '11 at 17:26
  • @hop ­— Yes, there is. If his list is length 9, for example, the index would turn into -1, which would only give him a one-element slice from the end of his list, instead of the 9 elements he would in fact want (assuming that, if he can't get ten, he wants “as close to ten as possible”). – Brandon Rhodes Dec 19 '11 at 18:41
  • sorry, i wasn't clear enough. it wouldn't be a problem if you did it right in the first place. the correct slice to get the last n elements of a list is _in_ _the_ _tutorial_. –  Dec 19 '11 at 19:39
  • @hop — ah, yes, I understand you! You are quite right: if he grabs the last *n* elements the usual Python way, then there is no problem with either subtraction or overflows at all. And, happily, several questions ignored his question — “why doesn't this work?” — and instead, quite properly, answered the question “why *shouldn't* I try making this work in the first place?” :) I just wanted to jump in and help him understand why his syntax hadn't worked, so that he understands that a list name must precede the slice notation. – Brandon Rhodes Dec 20 '11 at 02:04