get last two in a length of unknown length?

Tony Meyer t-meyer at ihug.co.nz
Wed Aug 18 22:58:05 EDT 2004


> I have a list of varying length. Would someone know the way 
> to get the last two values for this? I can see how this is 
> done with a list that I know the length of, but not one thats 
> generated by user input.

One way is to use the length of the list in your calculation, e.g:

>>> somelist = [1,2,3,4,5,6,]
>>> somelist[len(somelist)-1]
6
>>> somelist[len(somelist)-2]
5

However, a much better and simpler way is to simply count backwards:

>>> somelist = [1,2,3,4,5,6,]
>>> somelist[-2:]
[5, 6]

=Tony Meyer




More information about the Python-list mailing list