Worksheets › Class 9 › Python Lists › Cheat sheet
Class 9 Python Lists: cheat sheet
CBSE Computational Thinking and AI. A list holds many values in order. Items are found by index (from 0, or from −1 at the end), sliced, changed with methods and summed up with functions.
Key ideas
- Indexes start at 0, so a[0] is the first item and a[2] the third.
- Negative indexes count from the end: a[-1] is the last item, a[-2] the one before it.
- A slice a[i:j] gives the items from index i up to, but not including, index j.
- append(x) adds x at the end; insert(i, x) puts x at index i; extend adds every item of another list.
- remove(x) deletes the first x; pop() removes the last item and pop(i) the item at index i.
- sort() puts the list in ascending order; len, sum, max and min work on the whole list.
Remember
| a = [10, 20, 30, 40, 50] | a[0] = 10, a[3] = 40, a[-1] = 50 |
| Slices | a[1:3] = [20, 30]; a[:2] = [10, 20]; a[-3:-1] = [30, 40] |
| Functions | len(a) = 5, sum(a) = 150, max(a) = 50 |
| Methods | a = [5, 2, 8] a.append(1) # [5, 2, 8, 1] a.insert(0, 7) # [7, 5, 2, 8, 1] a.remove(2) # [7, 5, 8, 1] a.pop() # [7, 5, 8] |
Watch out
- Counting indexes from 1: a[1] is the SECOND item.
- Including the stop index in a slice: a[1:3] has two items, not three.
- Mixing up remove(x), which takes a value, with pop(i), which takes a position.
Worked example
num = [19, 77, 41, 66, 54, 51]. What is printed by (a) print(len(num)) (b) print(num[1:4]) (c) print(num[-4:-1])? For (b) and (c), write the items separated by commas.
Working: num[1:4] is the 2nd to 4th items; num[-4:-1] is the 3rd to 5th
Answer: (a) 6; (b) 77, 41, 66; (c) 41, 66, 54
Practise Python Lists
Revise with this page, then practise: every Python Lists sheet in the app is new, with an answer key and working.
Coming soon for Android and iPhone.