0.2 — Containers: Lists, Tuples, Sets, Dictionaries

Chapter 0 · Basics of Python

Prof. Xuhu Wan

Section 0.2 · Chapter 0 · Learning Statistics with Python

Containers: Lists, Tuples, Sets, Dictionaries

Basics of Python

Prof. Xuhu Wan

ISOM, HKUST Business School · 2026 Edition

Containers: Lists, Tuples, Sets, Dictionaries

Four ways to hold many values. You will predict which ones can be edited in place, which ones have positions, and — the trap that bites every analyst once — what happens to a when you change b.

Lists: ordered, mutable, mixed types

Predict the first line before you run.

nums = [10, 20, 30, 40]. What does print(nums[1:-1]) show?

print(nums[1:-1])

[20, 30]

[20, 30][10, 20, 30, 40, 50][10, 15, 20, 30, 40] removed: 5010 40 [15, 20]. append, insert, pop all edit the list in place — no assignment needed.

The aliasing trap

Two names, one list. Predict before running — this one costs people real money.

nums = [10, 20, 30, 40]; alias = nums; alias.append(50). What is nums now?

  • [10, 20, 30, 40]
  • It raises an error — nums is protected
  • [10, 20, 30, 40, 50]
  • [50, 10, 20, 30, 40]

Alias vs copy

nums: [10, 20, 30, 40, 50] alias: [10, 20, 30, 40, 50] then nums: [10, 20, 30, 40, 50] copy: [10, 20, 30, 40, 50, 15]. Assignment never copies; .copy() does. In Chapter 2 this returns as the SettingWithCopyWarning.

is asks about identity; == asks about value

nums = [10, 20, 30, 40]; alias = nums; fresh = [10, 20, 30, 40]. What do nums == fresh, nums is fresh, alias is nums give?

  • True True True
  • True False True
  • False False True
  • True False False

True False True. Use is only for None (x is None); use == for everything else.

Tuples: ordered and immutable

Parentheses instead of brackets, and one difference that matters. Predict.

coords = (34.05, -118.25); coords[0] = 0. What happens?

  • coords becomes (0, -118.25)
  • coords becomes (0,)
  • A ValueError
  • A TypeError — tuples do not support item assignment

See the error, then unpack

TypeError: 'tuple' object does not support item assignment. Unpacking (lat, lon = coords) is how you will receive the (sharpe, max_drawdown) pair from PerformanceMeasure in the projects.

Sets: unique, unordered

bag = {1, 2, 2, 3, 3, 3} — what does print(bag, len(bag)) show?

print(bag, len(bag))

{1, 2, 3} 3

{1, 2, 3} 3, True, {1, 2, 3, 4, 5}, {2}, {1, 2, 3}. set(tickers) is the one-line answer to “how many distinct tickers are in this file?”

Can you take the first element of a set?

What does bag[0] do for a set bag?

  • Returns the smallest element
  • Returns the first element inserted
  • Raises TypeError: 'set' object is not subscriptable
  • Returns 0

Dictionaries: key → value

A pandas Series is a dictionary that learned arithmetic; a DataFrame is a dictionary of columns. .keys(), .values(), .items() return in insertion order (Python ≥ 3.7).

Ask for a key that isn’t there

Before “gpa” is added, student = {“name”: “Alex”, “age”: 20, “skills”: […]}. What do student[“gpa”] and student.get(“gpa”, 0.0) do?

  • Both return None
  • The first raises KeyError; the second returns 0.0
  • Both raise KeyError
  • The first returns 0.0; the second raises KeyError

KeyError: 'gpa', then 0.0, then None. When df["Volumn"] throws a KeyError in Chapter 2, it is this exact mechanism — and the fix is a typo, not a .get.

Attributes vs methods

  • Attribute — a property you read: my_list.__class__, df.shape, df.columns.
  • Method — a function you call with (): my_list.append(3), text.upper(), df.head().

text = “tiger”. What is text.isalpha (no parentheses)?

  • True
  • False
  • The method object itself — not yet called
  • A SyntaxError

<class 'list'>, True, True, builtin_function_or_method. Rule for pandas: df.shape and df.columns (no brackets); df.head() and df.mean() (brackets). Forget the brackets and you print <bound method …> instead of a number.

Your turn: slice, de-duplicate, summarise

The notebook’s mini-exercise. From the list of 5 numbers nums5: (1) slice the middle three into middle3; (2) convert it to a set — what happens to the duplicate 20?; (3) build stats5 = {'min': …, 'max': …} with min() and max().

What you discovered

  • Lists edit in place (append, insert, pop); tuples refuse (TypeError); strings refuse too.
  • alias = nums is a second name, not a copy — use .copy() when you want independence.
  • == compares values, is compares identity; reserve is for None.
  • Sets collapse duplicates and have no positions (bag[0] fails); sorted(bag) gives you a list.
  • d[key] raises KeyError on a missing key; d.get(key, default) does not.
  • Attributes are read, methods are called — df.shape vs df.head().

Next: §0.3 — making decisions and repeating them: if, for, while, and the comprehension.