slices - handy summary

M

meridian

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

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 ]
 
D

Dustan

meridian said:
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 ]
 

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

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top