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:
num_list[0:9]
Any help would be great. Thanks in advance :)
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:
num_list[0:9]
Any help would be great. Thanks in advance :)
a negative index will count from the end of the list, so:
num_list[-9:]
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:]
The last 9 elements can be read from left to right using numlist[-9:], or from right to left using numlist[:-10:-1], as you want.
>>> a=range(17)
>>> print a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[-9:]
[8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[:-10:-1]
[16, 15, 14, 13, 12, 11, 10, 9, 8]