Python Forum
Need guidance on String indexing
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need guidance on String indexing
#1
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.
Reply
#2
When slicing the start is always included, and the end always excluded.
Reply
#3
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
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.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020