Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last items of a list in Python?

Tags:

python

list

slice

I need the last 9 numbers of a list and I'm sure there is a way to do it with slicing, but I can't seem to get it. I can get the first 9 like this:

num_list[0:9] 
like image 254
Nope Avatar asked Mar 14 '09 20:03

Nope


2 Answers

You can use negative integers with the slicing operator for that. Here's an example using the python CLI interpreter:

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

the important line is a[-9:]

like image 106
winsmith Avatar answered Oct 13 '22 23:10

winsmith


a negative index will count from the end of the list, so:

num_list[-9:] 
like image 23
cobbal Avatar answered Oct 14 '22 01:10

cobbal