Negative indexing python code

If anyone can please explain how the code in red square exactly works.

The top of the page seems to offer a pretty good (and visual!) explanation, really.

What the red box seems to be demonstrating is that you can mix and match postive and negative indices when slicing a string. Even in an otherwise unintuitive way. If you look at the illustration at the top, it’s clear that you’re starting from the -6th element and ending at (but excluding) the 1st (or 2nd, 3rd, and so on) element. Do note that the character at the starting index defined by the slice (here denoted by the negative index) is always included (except when you end up with an empty string) and the character at the ending index defined by the slice is always excluded.

If you think of using negative and postive indices in the opposite order, it does make quite a bit more sense, I feel:

print(word[0:-5])
print(word[0:-4])
print(word[0:-3])
print(word[0:-2])
print(word[0:-1])

that would result in identical output to the one with all negative indices. But it works exactly the same way as the example in red. You’re selecting one side using a postivie index and the other using the negative index.

With that said, the way this has been used in the red box is unlikely to be useful in practice. If you want a substring from the end of a string, you generally use negative indexing for both the start and the end, just like the block of examples before the red box. I’ve never had the need or desire to use negative indexing in this way. Maybe there’s some weird edge cases where it makes sense, but I’ve not come across these.

1 Like

Thanks for the explanation. The reason I had to use it is when I use the negative indexing I cant print the last “n” I can only print till ‘Pytho’ as end of index is exclusive.
print(word[-6:-1])
So to make it possible in negative indexing it only works with below example which is not making any sense to me…
print(word[-6:6])

If all you want to do is print the last 6 characters, then just omit the end index.

print(word[-6:])

Now, if you’re doing the programatically and you’re ending up wanting to get a slice from -6 to “-0”, then you’ve got yourself an edgecase that you need to consider separately.
Assuming you’ve got postitive numbers a and b you’ve found, where a >= b >= 0 (i.e b can be 0), you could do

word[-a: -b or len(word)]

That way you’d be getting a slice until the end of the word if b == 0 since 0 would evaluate to False in this context.
Or, if you want something more expressive, you could go for

word[-a, -b if b != 0 else len(s)]

or even

word[-a, -b if b != 0 else None]

Bah, you showed all variations except -b or None

Got to leave something for the imagination! :slight_smile:

1 Like