get last two in a length of unknown length?

Discussion in 'Python' started by M. Clift, Aug 19, 2004.

1. M. CliftGuest

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, Aug 19, 2004

2. M. CliftGuest

that should of course read list of unknown length : )

"M. Clift" <> wrote in message
news:cg1494\$lvr\$...
> 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, Aug 19, 2004

3. Paul McGuireGuest

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

Paul McGuire, Aug 19, 2004
4. Skip MontanaroGuest

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

Skip Montanaro, Aug 19, 2004
5. M. CliftGuest

Thankyou all for your help. Exactly what I needed : )

M. Clift, Aug 19, 2004
6. Phil FrostGuest

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

Phil Frost, Aug 19, 2004
7. M. CliftGuest

Cheers Phil : )

M. Clift, Aug 19, 2004
8. wes westonGuest

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

wes weston, Aug 19, 2004
9. M. CliftGuest

Again, thanks Wes, I appreciate it.

M. Clift, Aug 19, 2004