Question

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?

Was it helpful?

Solution

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']
>>> 

OTHER TIPS

There you go , this should give you a good idea

  l = ['h','e','l','l','o']
    print l[2:]
    #['l', 'l', 'o']
    print l[:2]
    #['h', 'e']
    print l[:-2]
    #['h', 'e', 'l']
    print l[-2:]
    #['l', 'o']

In your case, as someone has already suggested you can use, the bellow to print last two items in the list

print l[-2:]

But if you insist accesing the list from the start ,while not knowing what would be lenth of the list , you can use the following to print

 l[len(l)-2:]

Given a list a:

>>> a  = ['1','2','3','4']

You can reference the 3rd element from the end with -3.

>>> a[-3]
'2'

Specify a range from 3rd last to before the 2nd last (yes, that's just one.):

>>> a[-3:-2]
['2']

Specify a range from 3rd last to before the last:

>>> a[-3:-1]
['2', '3']

And specify a range from the 3rd last to after the last:

>>> a[-3:5]
['2', '3', '4']

It's kind of fun that way, is Python.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top