0
0
Pythonprogramming~10 mins

String indexing (positive and negative) in Python - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - String indexing (positive and negative)
Start with string
Index with positive number
Get character at that position
Index with negative number
Get character from end
Use character or error if out of range
We start with a string, then use positive or negative numbers to get characters by position. Positive counts from start, negative from end.
Execution Sample
Python
s = "hello"
print(s[1])
print(s[-1])
This code prints the second character and the last character of the string "hello".
Execution Table
StepExpressionIndex UsedCharacter RetrievedExplanation
1s = "hello"--String 'hello' is stored in variable s
2s[1]1eIndex 1 gets second character 'e' (counting from 0)
3s[-1]-1oIndex -1 gets last character 'o' (counting from end)
💡 All indexes are valid; program ends after printing characters.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
sundefined"hello""hello""hello"
Key Moments - 3 Insights
Why does s[1] give 'e' and not 'h'?
Because string indexing starts at 0, s[0] is 'h', so s[1] is the next character 'e' as shown in execution_table row 2.
What does a negative index like s[-1] mean?
Negative indexes count from the end of the string. s[-1] is the last character 'o', as shown in execution_table row 3.
What happens if the index is out of range?
Python will give an error. This example does not show that, but if you try s[10] on 'hello', it will cause an IndexError.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what character does s[1] retrieve?
A"h"
B"e"
C"l"
D"o"
💡 Hint
Check execution_table row 2 under 'Character Retrieved'
At which step does the program get the last character of the string?
AStep 3
BStep 2
CStep 1
DNo step gets the last character
💡 Hint
Look at execution_table row 3 where index -1 is used
If we change s[-1] to s[-2], what character would be retrieved?
A"o"
B"e"
C"l"
D"h"
💡 Hint
Negative index -2 means second last character; check variable s value in variable_tracker
Concept Snapshot
String indexing lets you get characters by position.
Positive index: 0 is first character.
Negative index: -1 is last character.
Example: s = "hello"; s[1] = 'e', s[-1] = 'o'.
Out of range index causes error.
Full Transcript
We start with a string variable s holding 'hello'. Using s[1] gets the second character 'e' because counting starts at zero. Using s[-1] gets the last character 'o' because negative indexes count from the end. If you try an index outside the string length, Python will give an error. This example shows how positive and negative indexing works step by step.