slices - handy summary
Dustan
DustanGroups at gmail.com
Wed Dec 13 06:11:41 EST 2006
meridian wrote:
> If, like me, you're always forgetting which way around your list/seq
> slices need to go then worry no more. Just put my handy "slice
> lookupper" (TM) ) on a (large!) PostIt beside your screen and, Hey
> Presto! no more tediously typing a 1-9 seq into your interpreter and
> then getting a slice just to check what you get.. (Yes you. You know
> you do that !) ... Cheers Steve
Actually, I don't. I just remember that, for a natural (positive
nonzero) number y:
x[:y] is the first y elements
x[-y:] is the last y elements
As shown here:
>>> x = range(5)
>>> x
[0, 1, 2, 3, 4]
>>> x[:2]
[0, 1]
>>> x[-2:]
[3, 4]
>>>
And I just work it out from there.
Just my method for remembering slices, that happens to work pretty well
for me.
> x = '0123456789'
>
> x[-10: ] 0123456789 x[ 0: ]
> x[ -9: ] 123456789 x[ 1: ]
> x[ -8: ] 23456789 x[ 2: ]
> x[ -7: ] 3456789 x[ 3: ]
> x[ -6: ] 456789 x[ 4: ]
> x[ -5: ] 56789 x[ 5: ]
> x[ -4: ] 6789 x[ 6: ]
> x[ -3: ] 789 x[ 7: ]
> x[ -2: ] 89 x[ 8: ]
> x[ -1: ] 9 x[ 9: ]
>
> x[ :-9 ] 0 x[ :1 ]
> x[ :-8 ] 01 x[ :2 ]
> x[ :-7 ] 012 x[ :3 ]
> x[ :-6 ] 0123 x[ :4 ]
> x[ :-5 ] 01234 x[ :5 ]
> x[ :-4 ] 012345 x[ :6 ]
> x[ :-3 ] 0123456 x[ :7 ]
> x[ :-2 ] 01234567 x[ :8 ]
> x[ :-1 ] 012345678 x[ :9 ]
> 0123456789 x[ :10 ]
More information about the Python-list
mailing list