Python Forum

Full Version: Need guidance on String indexing
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Am learning Python for school and reading a Python textbook, I come across one part that I don't understand.

>>> grades = ['A', 'B', 'C', 'D', 'F']
>>> grades[2:4]
['C', 'D']
Going by the Python String Indexing logic, the first position starts from 0 so by logic, 'A' is 0 and the output 'C' is correct which is 2. But I don't understand why 4 is 'D' when it should been 'F' instead since Indexing starts from 0.

Is there a mistake in the book? or am I missing something here? Please advise, thanks.
When slicing the start is always included, and the end always excluded.
I like to think of slicing as the indexes being between numbers:

Output:
['A', 'B', 'C', 'D', 'E'] ^ ^ ^ ^ ^ ^ | | | | | | 0 1 2 3 4 5
If you just index (grades[3]) you get the item after the index ('D'). And if you get a full slice (grades[2:4]), you get everything between the numbers (['C', 'D']).

Of course, understanding it the way Yoriz explained it is good to, because that's the way range() works.
Add-on way to think: how many characters should slice [2:4] return? 4 - 2 = 2 (it’s always stop- start = number of elements). If first is included then last should be excluded in order to get right number of characters.