Practice question · Sort into groups
For a list of length 4 (valid indices 0 through 3), sort each index by whether accessing it is valid.
Groups: Valid index · Out of range
- 4
- 0
- 3
- 2
- 5
Hints
- In a list of length n the valid indices are 0 through n minus 1.
- For length 4 the last valid index is 3, so 4 is already one too far.
Show the answer
Valid index: 0, 3, 2
Out of range: 4, 5
Why
Valid indices run 0 to 3 for a four-item list, so 0, 2 and 3 are fine while 4 and 5 run off the end. Accessing index 4 here is the index-out-of-range error, and it stems from forgetting that counting starts at 0.
Practise Basic Data Collections
The app has 7 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.
More questions on Basic Data Collections
- Select every statement that is true of lists and dictionaries as the lesson describes them.
- A list preserves order and allows duplicates; a set does neither and can test membership far faster. Why does…
- A list stores elements by sequential position, whereas a dictionary associates values with unique keys. What…