Learning Python, have a tiny puzzler

Hey guys,

Learning Python, and more about programming in general.

One thing I noticed is that it doesn’t make sense to me why the slicing order is different for negative values than for positives…

With a positive value, having the colon first means it grabs the first two characters of the string…

>>> word[:2]    # The first two characters
'He'
>>> word[2:]    # Everything except the first two characters
'lpA'

But with negative value, having the colon last means it grabs the last two characters of the string…

>>> word[-2:]    # The last two characters
'pA'
>>> word[:-2]    # Everything except the last two characters
'Hel'

It seems to me like it should instead be “colon first to slice n characters, colon last to slice everything except n characters”. But I’m probably just looking at it the wrong way. :): It must have been designed this way for a good reason?

Probably will make more sense as I learn more…

I like to think of it this way (probably not accurate to what’s happening internally, but it’s worked for me :cool:):

[:2] = Start at the beginning of the list and read forward 2 elements (exclusive)
[2:] = Start 2 elements from the beginning of the list and read forward to the end

[:-2] = Start at the beginning of the list and read till 2 elements from the end
[-2:] = Start 2 elements from the end of the list and read forward to the end

Ah, cool. I like it your way. :slight_smile:

From the docs:

One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:

±–±–±–±–±–+
| H | e | l | p | A |
±–±–±–±–±–+
0 1 2 3 4 5
-5 -4 -3 -2 -1

The first row of numbers gives the position of the indices 0…5 in the string; the second row gives the corresponding negative indices.

hmm… sorry the formatting is hard to read – here is the page:

about half way down the page.

Yeah, the numbering makes sense, I was having a bit of cognitive dissonance with the positioning of the colon. I like the “start from here” analogy.