slices - handy summary

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • meridian

    #1

    slices - handy summary

    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 ]

  • Dustan

    #2
    Re: slices - handy summary


    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 ]

    Comment

    Working...