Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I "count from the back" in python lists?

Say I have a list
l = ['h','e','l','l','o']
I want to be able to take the last two items and use them, but I don't know how long the list
is(It's user input). So can't do l[3:] because what if the list is seven(or any number) items long instead of five?

How can I count from the back of the list?

like image 422
Awalrod Avatar asked Dec 04 '22 10:12

Awalrod


1 Answers

print l[-2:]

Negative numbers count from the end.

>>> l = ['h','e','l','l','o']
>>> print l[-2:]
['l', 'o']
>>> print l[-5:]
['h', 'e', 'l', 'l', 'o']
>>> print l[-6:]
['h', 'e', 'l', 'l', 'o']
>>> 
like image 160
Jonathan Leffler Avatar answered Dec 16 '22 21:12

Jonathan Leffler