P01.6 · Lists, tuples, dictionaries and sets
P01.6 L0 · Foundation 4 lessons · about 100 min Live · in review
Part of P01 Python from Zero in the Programming and Data track.
Real programs keep many values together: five quiz scores, one student’s record, a count for every band, a number for every word. These four lessons draw each container as the course’s box diagram, a row of numbered slots or a two-column table, and use it to index, slice and change a list, to unpack tuples and walk two lists in step, to count with a dictionary and to compare sets. The last lesson shows what the arrows mean: two names can share one list, and a copy is the only way to break the link.
What you need first. Values, names and the memory diagram (P01.2), loops over a list written in square brackets (P01.3), functions and the call stack (P01.4), and import (P01.5), which the last two lessons use for collections.Counter and copy.deepcopy.
Lessons
Lists: ordered and changeable P01.6.1 25 min
A list is a numbered row of slots. Read any item by its position, counted from 0 at the front or from -1 at the back, cut out a slice, and change the list in place with append, insert, pop and remove, all on the five quiz scores of the study table.
Tuples, unpacking and looping in pairs P01.6.2 25 min
A tuple is a row of values that cannot be changed, the right shape for a record such as (‘Ama’, 2, 55). Pack and unpack tuples, swap two names in one line, return two values from a function, and walk two lists in step with zip to find the mean squared error of predict, 8.0.
Dictionaries and sets P01.6.3 25 min
A dictionary finds a value by its key, drawn as a two-column table. Look up, add and overwrite by key, test with in and get, count the five bands of the study table from scratch and then with Counter, and meet sets: no duplicates, a quick in, union, intersection and difference.
Sharing, copying and nesting P01.6.4 25 min
Two names can share one list, so a change made through one shows through the other until a copy breaks the link. Tell a == b from a is b, see the same sharing in function calls and in a default argument, and copy the nested study table safely with copy.deepcopy.
The interactive
P01.6-X1 · Box-diagram workbench. A list drawn as a row of slots under the name a. Append, pop, insert and assign, make b with b = a or with b = a.copy(), then change the list through either name and watch whether the other one changes too. A read-out gives a == b and a is b after every step. It lives in Sharing, copying and nesting.