Module 5: Lists and tuples

Store many values: lists, the aliasing trap, list patterns, nested lists, stacks, comprehensions and tuples.

  1. Lists: append adds one item, extend adds many; remove takes a value, pop an index; sort() changes the list and returns None, sorted() returns a new list.
  2. Lists and names: the aliasing trap: b = a gives one list two names; copy with a[:], list(a) or a.copy() (and copy.deepcopy for nested lists); build grids with a loop, never [[0]n]n.
  3. List patterns: Start a max/min at lst[0], a sum at 0; return -1 only after the whole search loop; swap with a[i], a[j] = a[j], a[i].
  4. Nested lists: tables and matrices: A table is a list of rows: m[r][c]; len(m) is rows, len(m[0]) is columns; build each new row inside the loop.
  5. Stack, queue and list comprehensions: Stack: append + pop() (LIFO); queue: append + pop(0) or deque.popleft() (FIFO); [f(x) for x in xs if cond] builds a new list.
  6. Tuples: Tuples are fixed lists: the comma makes one ((5,), not (5)); a, b = b, a swaps; return x, y returns a tuple you can unpack.

Ends with a 14-question checkpoint (80% passes) and a mini project: Class marks register.