← Python for Data Analysis

PDA·03 · Chapter 3

Built-In Data Structures, Functions & Files

Chapter 3 — the containers, functions and file handling pandas is built on

Seven sessions on the parts of plain Python that data code leans on hardest: the four built-in containers, slicing, comprehensions, functions as values, generators, error handling, and reading and writing files.

3.1

Tuples

  • A tuple is a fixed-length, immutable sequence: tup = (4, 5, 6), or just 4, 5, 6 — the commas make the tuple, not the parentheses.
  • tuple() converts any sequence: tuple("string") gives ('s', 't', 'r', 'i', 'n', 'g').
  • The tuple can't change, but an object inside it can: if slot 1 holds a list, tup[1].append(3) works.
  • Unpacking assigns each element to a name: a, b, c = tup. It makes swapping one line: a, b = b, a.
  • *rest collects "everything else": a, b, *rest = values. By convention *_ means "values I don't need".
Tuple
an immutable, ordered sequence
Unpacking
assigning a sequence's elements to several names at once
*rest
captures the remaining elements as a list
count()
how many times a value appears
values = 1, 2, 3, 4, 5
a, b, *rest = values
print(a, b, rest)

a, b = 1, 2
a, b = b, a
print(a, b)

seq = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
for x, y, z in seq:
    print(f"x={x}, y={y}, z={z}")
1 2 [3, 4, 5]
2 1
x=1, y=2, z=3
x=4, y=5, z=6
x=7, y=8, z=9
Activity 1

Store a student record as a tuple (name, class, score). Unpack it into three variables and print a sentence with an f-string.

Activity 2

Given scores = (55, 72, 91, 64, 88), use unpacking with *middle to get the first, last and everything in between.