get last two in a length of unknown length?

M

M. Clift

Hi All,

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.

Thanks for any help
 
M

M. Clift

M. Clift said:
Hi All,

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.

Thanks for any help
 
P

Paul McGuire

M. Clift said:
Hi All,

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.

Thanks for any help
Use negative index values to count backwards from the end of a list or
tuple.

x = [ 0, 1, 2, 3, 4]

x[-1] gives 4
x[-2] gives 3
x[-2:] gives [3,4] <- this is called "slice" notation

You will find *many* more interesting and fun facts in the Python Tutorial.

-- Paul
 
S

Skip Montanaro

MC> I have a list of varying length. Would someone know the way to get
MC> the last two values for this?

mylist[-2:]

Skip
 
P

Phil Frost

A negative index counts from the end, so:

l = [0,1,2,3,4]
l[-1] == 4

this works for slices too:

l[-2:] == [3,4]
 
W

wes weston

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top