Exercise 0.1: Indices and slices: ten expressions to evaluate
The variable s holds the string 'ALGORITHM'. Give the value of each expression, or the error that Python raises.
Method: the characters are numbered from 0 on the left, so the last one has the index len(s) - 1; a negative index counts from the end, -1 being the last character. A slice s[a:b] takes the characters from index a up to index b, b excluded; without a it starts at the beginning, without b it runs to the end. An index outside the string raises an IndexError; a slice never does.
- a) len(s)
- b) s[1]
- c) s[8]
- d) s[9]
- e) s[-2]
- f) s[2:5]
- g) s[:3]
- h) s[6:]
- i) s[5:50]
- j) len(s[3:7])
Show the solution
Answers
- a) 9
- b) 'L'
- c) 'M': the last index is 8
- d) IndexError
- e) 'H'
- f) 'GOR': indices 2, 3 and 4
- g) 'ALG'
- h) 'THM'
- i) 'ITHM', no error
- j) 4, that is 7 - 3
Write the indices under the letters: A 0, L 1, G 2, O 3, R 4, I 5, T 6, H 7, M 8. The negative indices run from -9 under the A to -1 under the M.
len counts the characters: 9. The indices go from 0 to 9 - 1 = 8.
s[1] is the second character: 'L'.
Pitfall: counting from 1 and answering 'A', which is s[0].
s[8] is 'M', the last character: its index is len(s) - 1 = 8.
s[9] asks for a tenth character, which does not exist: IndexError: string index out of range. The program stops on that line.
-1 is the 'M' and -2 the 'H': s[-2] is the same character as s[9 - 2], that is s[7].
In Java, a negative index is an error: the last character is s.charAt(s.length() - 1).
s[2:5] takes the indices 2, 3 and 4: 'GOR', 5 - 2 = 3 characters.
Pitfall: including s[5] and answering 'GORI'. The end of a slice is excluded.
s[:3] starts at index 0 and stops before index 3: 'ALG', the first 3 characters.
s[6:] runs from index 6 to the end: 'THM'.
A slice whose end goes past the string stops at its last character: s[5:50] is s[5:], 'ITHM'.
No error: only a single index outside the string raises an IndexError.
s[3:7] is 'ORIT', and its length is 7 - 3 = 4. Inside the string, a slice s[a:b] has b - a characters.