Lesson 4

Collections, Indexing, and Slicing

Big question

How should related values be organized so that the structure communicates what operations are legitimate?

Lesson progress

Complete checkpoints as you learn

0% complete0 checkpoint streak
Progress tracking available after sign-in. Sign in to save your work.
Big question
Concept
Activity
Quiz

Learning objectives

  • Use lists, tuples, dictionaries, and sets.
  • Index and slice ordered collections.
  • Build nested structures.
  • Choose a collection based on meaning rather than habit.
  • Prerequisites: Chapter 3.
  • Key terms: list, tuple, dictionary, set, index, slice.

Simple explanation

A list promises order and permits change. A tuple promises order and is normally treated as fixed. A dictionary maps unique keys to values. A set stores unique elements without meaningful position. These distinctions are analytical: a portfolio of ticker weights is naturally a dictionary, a fixed coordinate may be a tuple, and a sequence of monthly returns is a list until it becomes a NumPy array or pandas Series.

Key terms

lists, tuples, dictionaries, and sets
A core idea in Chapter 4 that students apply carefully in economic analysis.
Index and slice ordered collections
A core idea in Chapter 4 that students apply carefully in economic analysis.
Build nested structures
A core idea in Chapter 4 that students apply carefully in economic analysis.
Choose a collection based on meaning rather than habit
A core idea in Chapter 4 that students apply carefully in economic analysis.
Prerequisites: Chapter 3
A core idea in Chapter 4 that students apply carefully in economic analysis.
Key terms: list, tuple, dictionary, set, index, slice
A core idea in Chapter 4 that students apply carefully in economic analysis.

Analytical workflow

Question+data+assumptions+transparentPython>evidenceQuestion + data + assumptions + transparent Python -> evidence

Interpret the expression in words and units before using it in a claim.

Example

Interpretation. The slice includes positions 1, 2, and 3, but not 4.

Prerequisites

  • Complete the preceding course chapters or review their summaries as needed.

Full theory and examples

4.2

Four structures, four promises

A list promises order and permits change. A tuple promises order and is normally treated as fixed. A dictionary maps unique keys to values. A set stores unique elements without meaningful position. These distinctions are analytical: a portfolio of ticker weights is naturally a dictionary, a fixed coordinate may be a tuple, and a sequence of monthly returns is a list until it becomes a NumPy array or pandas Series.

4.3

Indexing is positional, slicing is a window

Python begins indexing at zero. The first element is therefore position 0, while -1 means the last element. Slices use a half-open interval: the starting position is included and the stopping position is excluded. That design makes lengths predictable, because values[a:b] contains b-a positions when the bounds are valid. The same convention appears in strings, arrays, and many pandas operations.

4.4

Comprehensions compress a transformation

List and dictionary comprehensions express a simple transformation or filter in one readable line. They are useful when the logic is short and transparent. A comprehension with several nested conditions becomes a puzzle and should be replaced by a loop or function. Readability is not cosmetic; it allows the analyst to inspect whether a data transformation matches the intended research rule.

4.5

Python demonstrations

4.5.1

Demonstration 4.1: Index and slice a return series

Verified output

Interpretation. The slice includes positions 1, 2, and 3, but not 4.

4.5.2

Demonstration 4.2: Map assets to weights

Verified output

Interpretation. A dictionary preserves the relationship between each asset label and its weight.

4.6

Visual evidence

4.7

Reference table

Why This Matters

Collection choice makes assumptions visible before the data reach a model.

Common Mistake

Using a set when order matters. A set is excellent for membership tests but cannot represent a time sequence.

Ceteris LAB Tip

Say the structure aloud: “a mapping from series name to unit” suggests a dictionary; “an ordered sequence of returns” suggests a list or array.

R-to-Python / Source Bridge

The old notes introduced vectors and matrix-like objects early. Python separates general-purpose collections from numerical arrays, which are introduced in Chapter 8.

Table 4. Chapter reference.
StructureOrdered?Duplicates?Best use
listYesYeschangeable sequence
tupleYesYesfixed record or coordinate
dictInsertion orderKeys uniquenamed mapping
setNo positional meaningNomembership and uniqueness

Visual evidence

Figure 4. Lists, tuples, dictionaries, and sets encode different structural promises.
Figure 4. Lists, tuples, dictionaries, and sets encode different structural promises.

Additional Python demonstrations

Live Python

Source demonstration 2

Source demonstration 2

Stdout

Run Python to see results here.

Status / stderr

Ready to run Python in your browser.

Line-by-line guide

  1. Line 1Create or update a Python object used in the analysis.
  2. Line 2Display a result so students can inspect the output.
  3. Line 3Create or update a Python object used in the analysis.
  4. Line 4Display a result so students can inspect the output.

Verified source output

0.012 -0.011 [-0.004, 0.009, 0.003]
1.0 ['BOND', 'EQUITY']
0.012
-0.011
[-0.004, 0.009, 0.003]
1.0
['BOND', 'EQUITY']

Interpretation. The slice includes positions 1, 2, and 3, but not 4.

Interpretation. A dictionary preserves the relationship between each asset label and its weight.

Guided practice

  1. 1Re-run Demonstration 4.1 and change one input while keeping the analytical question fixed.
  2. 2Explain in two sentences how the output supports, or fails to support, the chapter opening question.
  3. 3Add one validation check that would prevent a plausible error.

Exercises

  1. 1Create a list of five GDP growth rates and print the middle three.
  2. 2Create a tuple containing a series ID and frequency.
  3. 3Create a dictionary mapping three variables to units.
  4. 4Use a set to remove duplicate province codes.

Source and downloads

Chapter 4 of Fundamentals of Python for Financial Econometrics by Mohammad Safavi, Ph.D.. The lesson is an original Ceteris Lab web adaptation of the supplied publication package.

Live Python

Collections, Indexing, and Slicing: live Python

Collections, Indexing, and Slicing: live Python

Stdout

Run Python to see results here.

Status / stderr

Ready to run Python in your browser.

Line-by-line guide

  1. Line 1Create or update a Python object used in the analysis.
  2. Line 2Display a result so students can inspect the output.
  3. Line 3Display a result so students can inspect the output.
  4. Line 4Display a result so students can inspect the output.

Python walkthrough

  1. 1`returns = [0.012, -0.004, 0.009, 0.003, -0.011]`: Creates or updates a named object used by later steps.
  2. 2`print(returns[0])`: Displays a result so it can be checked and interpreted.
  3. 3`print(returns[-1])`: Displays a result so it can be checked and interpreted.
  4. 4`print(returns[1:4])`: Displays a result so it can be checked and interpreted.

Live notebook

Run this lesson as a notebook

Open an editable notebook cell-by-cell, run Python in the browser, and download the `.ipynb` file for later.

Related dataset

Ceteris Lab teaching sample

Estimated time

25 to 40 min

Packages

pandas, numpy

Expected output

Printed Python results that can be compared with the lesson explanation.

Learning goals

  • Load and inspect Ceteris Lab teaching sample.
  • Run the Python cells connected to Collections, Indexing, and Slicing.
  • Interpret the output using lists, tuples, dictionaries, and sets and Index and slice ordered collections.

Common errors

  • File not found: check that wage_sample.csv is installed or use the course data folder.
  • Package import error: use the browser notebook first, then download for local Jupyter if your local packages differ.
  • Column name error: compare your variable names with the dataset variables listed for this notebook.

Dataset path helper

import pandas as pd

df = pd.read_csv("/data/wage_sample.csv")
df.head()

Interactive activity

Chapter 4 interactive

Reproducible Python decision lab

Evidence strength: 55%
Fragile workflowReproducible workflow

Which step should come before trusting a successful Python run?

Immediate feedback

Choose a decision, then test how the claim changes as evidence becomes stronger or weaker.

Try it yourself

Write one plain-English sentence explaining the main idea from this lesson.

Common mistakes

Check these before you move on.

Return to the lesson assumptions, units, diagnostics, and source evidence to replace this shortcut with a defensible interpretation.

Quick quiz

Which statement best answers the Chapter 4 opening question: How should related values be organized so that the structure communicates what operations are legitimate?

Quick quiz

Which practice should be avoided when applying Collections, Indexing, and Slicing?

Quick quiz

What is the most defensible way to interpret the Python demonstration?

Quick quiz

Why does Chapter 4 matter in an applied econometrics workflow?

Key takeaway

Lists, tuples, dictionaries, and sets encode different structural assumptions. Zero-based indexing and half-open slicing recur throughout Python. Comprehensions are best kept simple.