Worksheets › Class 11 › Lists › Cheat sheet
Class 11 Lists: cheat sheet
CBSE Computer Science. Lists are mutable, ordered sequences: indexing and slicing, + and *, the list methods and what they return, nested lists, copying, and the standard list programs.
Key ideas
- Lists are mutable: L[i] = x changes an item in place; indexing and slicing work as they do for strings.
- append(x) adds one item at the end, extend(L2) adds every item of L2, and insert(i, x) puts x at index i.
- remove(x) deletes the first x (a ValueError if there is none); pop() removes and gives back the last item, pop(i) the item at index i.
- append, extend, insert, remove, sort and reverse change the list and give back None, so L = L.sort() leaves L as None.
- sorted(L) gives a new sorted list and leaves L as it was; L.sort() sorts L itself.
- M = L gives a second name for the same list; L.copy(), list(L) or L[:] makes a separate copy.
- In a nested list M[i][j] is row i, column j, both counted from 0.
Remember
| L = [10, 20, 30, 40] | L[1] = 20, L[-1] = 40, L[1:3] = [20, 30], L[::-1] = [40, 30, 20, 10] |
| Operators | [1, 2] + [3] = [1, 2, 3]; [0] * 3 = [0, 0, 0]; 3 in [1, 2, 3] is True |
| Methods | L = [5, 2, 8] L.append(1) # [5, 2, 8, 1] L.insert(0, 7) # [7, 5, 2, 8, 1] print(L.pop()) # 1 L.sort() # [2, 5, 7, 8] |
| append or extend | L.append([3, 4]) adds one item, a list; L.extend([3, 4]) adds 3 and then 4 |
| Functions | len(L), sum(L), max(L), min(L); L.count(x); L.index(x) gives the first position |
| Mean of a list | sum(L) / len(L) is a float: [4, 5, 9] gives 6.0 |
| Copy or not | M = L; M.append(9) changes L too; with M = L[:] it does not |
Watch out
- Writing L = L.sort(): sort() gives back None.
- Mixing up remove(x), which takes a value, with pop(i), which takes an index.
- Thinking M = L copies the list: both names share one list.
- Using append() to add several items: append([3, 4]) adds one list inside the list.
Worked example
What does this program print? L = [47, 9, 35, 15, 31, 38, 58, 39] for i in range(0, len(L) - 1, 2): L[i], L[i + 1] = L[i + 1], L[i] print(L)
Working: items at even and odd positions swap in pairs; a last odd item stays
Answer: [9, 47, 15, 35, 38, 31, 39, 58]
Practise Lists
Revise with this page, then practise: every Lists sheet in the app is new, with an answer key and working.
Coming soon for Android and iPhone.