Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does s[len(s)-1:-1:-1] not work?

In looking at some python strings and functions, I discovered this strange quirk of python:

s = "hello"
print s[::-1]

which then prints: olleh

However, print s[len(s)-1:-1:-1] doesn't work. My understanding is that it should iterate from the last element s[len(s)-1] to the first element s[0]. However, it just prints an empty string '', which I believe is because in strings of some given length (say, 5), s[4] == s[-1]. But, I don't understand why python decides to use -1 instead of 4, which is the actual len(s).

Furthermore, s[len(s):0:-1] + s[0] works. Why is len(s) a valid index? Does python just convert len(s) to 0 arbitrarily?

P.S. This is in Python 2.7.8, I'm not sure if it also works in 3.x.x

EDIT: Confirmed to be the same in Python 3

like image 628
Vasu Avatar asked Sep 17 '14 04:09

Vasu


People also ask

Why Len is not a method?

The fact that len is a function means that classes cannot override this behaviour to avoid the check. As such, len(obj) gives a level of safety that obj. len() cannot.

What does [- 1 :] mean in Python?

Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.

How does LEN () work in Python?

The len() function returns the number of items in an object. When the object is a string, the len() function returns the number of characters in the string.

What does the LEN () function do?

LEN returns the number of characters in a text string. LENB returns the number of bytes used to represent the characters in a text string.


1 Answers

The slice notation is this:

s[start:stop:step]

specifically, stop being up to but not including it. Translate this to what you're asking:

s[len(s)-1:-1:-1]

This is, based on the length of 5 for 'hello'

s[4:-1:-1]

or

s[4:4:-1]

which is an empty, or zero-length string.


I have given a much more in-depth exposition of the slice notation here: Explain Python's slice notation

like image 123
Russia Must Remove Putin Avatar answered Sep 21 '22 00:09

Russia Must Remove Putin