- Know list, array and dictionary, their purpose and when each is used (2.3.1)
- Interpret, develop and debug code using data structures (2.3.2–2.3.4)
Data structures
A data structure stores a collection of values under one name so they can be accessed and processed together.
List
An ordered, changeable collection. Items are accessed by index, starting at 0, and can be of different types.
names = ["Ali", "Bea", "Cal"]
names.append("Dev") # add to the end
names.insert(1, "Ana") # insert at index 1
names.remove("Cal") # remove a value
print(names[0], len(names)) # Ali 4
Use when you need a sequence that grows or shrinks, such as a queue of orders.
Array
An ordered collection where every item is the same data type. In Python you can use the array module. Because the type is fixed, arrays use memory efficiently.
import array
readings = array.array("i", [12, 15, 11])
readings.append(14)
print(readings[1]) # 15
Use when you store lots of values of one type, such as sensor readings.
Dictionary
A collection of key: value pairs. Each key is unique and is used to look up its value.
stock = {"pen": 40, "ruler": 12}
stock["pen"] = stock["pen"] - 1
print("ruler" in stock) # True
Use when you need to find data by a meaningful label rather than a position.
Useful commands from Appendix 2
index(), append(), insert(), remove(), count(), pop(), sort(), in, not in, len().
Comparing them
| Structure | Ordered | Access by | Mixed types | Best for |
|---|---|---|---|---|
| List | Yes | Index | Yes | General sequences |
| Array | Yes | Index | No | Many values of one type |
| Dictionary | By insertion | Key | Yes (values) | Looking things up by label |
Common bugs
- Using an index that does not exist (
IndexError), such asnames[4]in a 4-item list. - Looking up a key that is not there (
KeyError); check withinfirst. - Forgetting that the first index is 0, not 1.