Velocity Reviews > get last two in a length of unknown length?

# get last two in a length of unknown length?

M. Clift
Guest
Posts: n/a

 08-19-2004
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. Clift
Guest
Posts: n/a

 08-19-2004

"M. Clift" <(E-Mail Removed)> wrote in message
news:cg1494\$lvr\$(E-Mail Removed)...
> 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
>
>

Paul McGuire
Guest
Posts: n/a

 08-19-2004
"M. Clift" <(E-Mail Removed)> wrote in message
news:cg1494\$lvr\$(E-Mail Removed)...
> 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

Skip Montanaro
Guest
Posts: n/a

 08-19-2004

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

M. Clift
Guest
Posts: n/a

 08-19-2004
Thankyou all for your help. Exactly what I needed : )

Phil Frost
Guest
Posts: n/a

 08-19-2004
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]

On Thu, Aug 19, 2004 at 03:45:47AM +0100, M. Clift wrote:
> 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. Clift
Guest
Posts: n/a

 08-19-2004
Cheers Phil : )

wes weston
Guest
Posts: n/a

 08-19-2004
M. Clift wrote:
> 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,
Note this, maybe, unexpected behavior:

>>> list=[1]
>>> list[-2:]

[1]

>>> list = []
>>> list[-2:0]

[]

wes

M. Clift
Guest
Posts: n/a

 08-19-2004
Again, thanks Wes, I appreciate it.