Python, from Zero, for AI · Chapter 02
Choosing the shape of your data
1:51 · Narrated with a synthetic voice. Captions are available in the player.
Read the transcript
The second module is about holding more than one thing. A list is positions in order, where the order is part of the meaning and duplicates are ordinary. A dictionary is named slots, where one name means exactly one slot, so writing to the same name twice replaces rather than adds. The honest answer to which one you need is usually both, nested: a list of turns, each turn a small dictionary with a role and some content. Some chat APIs use a list of message records with fields like these. Others use a different schema. Practise with the local records in this chapter, then check the current interface and any charges before sending real data. Then the module does something a beginner course usually skips: it costs the choice. Asking whether an item is in a list makes Python compare it against each element in turn, so the time grows with the length of the list. Asking whether it is in a set hashes the value once and looks in one place, at effectively constant cost. On a hundred thousand items that is four orders of magnitude, and a placement script that took twenty-six minutes finished in fifty-one seconds after one line changed. That is not a trick for experts. It is the difference between a script you can run whenever the data changes and one you run overnight and hope.