Worksheets › Class 11 › Working with Lists and Dictionaries › Cheat sheet
Class 11 Working with Lists and Dictionaries: cheat sheet
CBSE Informatics Practices. Lists: indexing, slicing, operators and methods; dictionaries: keys and values, adding, updating, deleting and traversing them.
Key ideas
- List indexes start at 0, and a negative index counts from the end: a[-1] is the last item.
- a[i:j] runs from index i up to, not including, j; a[::2] takes every second item and a[::-1] reverses.
- + joins two lists and * repeats one; on lists they never do arithmetic on the items.
- append(x) adds one item at the end, extend(L) adds each item of L, insert(i, x) puts x at index i; pop() removes and returns the last item, pop(i) the item at i, remove(x) the first x.
- count(x) counts x and index(x) finds its first position; sort() sorts the list itself (reverse=True: largest first).
- A dictionary maps unique, immutable keys to values; d[k] = v replaces the value of an existing key or adds a new pair at the end, and del d[k] removes it.
- x in d checks the keys only; keys(), values() and items() follow the order the keys were added, and d1.update(d2) adds the pairs of d2, replacing the values of shared keys.
Remember
| a = [10, 20, 30, 40, 50] | a[1] → 20; a[-1] → 50; a[1:4] → [20, 30, 40]; a[::2] → [10, 30, 50] |
| + and *; built-ins | [1, 2] + [3] → [1, 2, 3]; [1, 2] * 2 → [1, 2, 1, 2]; for [4, 9, 2]: len 3, min 2, max 9, sum 15 |
| pop and remove | pop() removes the LAST item and returns it; remove(x) removes the first x, by value |
| Third largest | a.sort() then a[-3]; third smallest: a[2] |
| Dictionary | d = {'Asha': 78}; d['Asha'] = 81 updates; d['Ravi'] = 64 adds; del d['Ravi'] removes |
| len(d) after changes | updating a key: no change; a new key: one more; del: one fewer |
| Traversing | for k in d: if d[k] >= 75: print(k) # keys in the order added |
Watch out
- Counting the first item as index 1: a[2] is the third item.
- Including the stop index in a slice: a[1:4] has three items, not four.
- Thinking 78 in d checks the values: in looks at the keys only.
- Confusing append([3, 4]), which adds one item (a list), with extend([3, 4]), which adds two.
Worked example
Answer (a) to (c) for this program. a = [45, 47, 6, 37, 27] a.extend([63, 73]) a.insert(1, 6) p = a.pop() print(p) print(len(a)) print(a.index(6))
Working: after insert: [45, 6, 47, 6, 37, 27, 63, 73]; pop() removes the last item
Answer: (a) 73; (b) 7; (c) 1
Practise Working with Lists and Dictionaries
Revise with this page, then practise: every Working with Lists and Dictionaries sheet in the app is new, with an answer key and working.
Coming soon for Android and iPhone.