Lesson 02 · foundations
The core structures that pandas DataFrames are built on underneath.
Before diving into pandas, you need to understand how Python natively holds collections of data. Underneath all the complex DataFrame operations, you'll find these three foundational structures: lists, dictionaries, and tuples.
Lists are ordered collections. They are 0-indexed, mutable (can be changed in place), and allow duplicate elements.
# Creating a list of closing prices
prices = [100.5, 102.3, 98.7, 105.0]
# Indexing (0-based)
first = prices[0] # 100.5
last = prices[-1] # 105.0
# Slicing: [start:stop] (stop is exclusive)
mid = prices[1:3] # [102.3, 98.7]
early = prices[:2] # [100.5, 102.3]
late = prices[2:] # [98.7, 105.0]
# Mutating
prices.append(107.2) # Adds to the end
prices[0] = 99.8 # Modifies the first element
Other common operations include len(prices) to get the count, prices.pop() to remove the last item, prices.sort(), and prices.reverse().
List Comprehensions are a concise way to create lists. This pattern is critical for data work:
# Apply a 10% return to all prices
inflated = [p * 1.1 for p in prices]
Dictionaries (dicts) map keys to values. They are fast, mutable, and maintain insertion order (since Python 3.7).
# Creating a dict
stock = {
"ticker": "AAPL",
"price": 150.25,
"volume": 1_200_000
}
# Accessing values
px = stock["price"] # 150.25
div = stock.get("dividend", 0) # 0 (safe access with default)
# Adding or updating
stock["sector"] = "Technology"
stock["price"] = 152.10
# Iterating
for key, val in stock.items():
print(f"{key}: {val}")
# also .keys(), .values()
You can also use Dict Comprehensions:
prices_dict = {"AAPL": 150, "MSFT": 310}
inflated_dict = {k: v * 1.1 for k, v in prices_dict.items()}
Tuples are ordered collections just like lists, but they are immutable—they cannot be changed after creation.
# Creating a tuple (parentheses are optional but common)
point = (3, 5)
trade = "BUY", "AAPL", 150.25
# Unpacking
action, ticker, price = trade
Why use tuples? Because they are immutable, they are safer for fixed data, they can be used as dictionary keys (unlike lists), and they are standard for returning multiple values from a function.
.iterrows(), pandas returns each row as a tuple of (index, Series). DataFrame index entries themselves are also built on tuples.
| Structure | Syntax | Ordered? | Mutable? | When to use? |
|---|---|---|---|---|
| List | [1, 2] |
Yes | Yes | Homogeneous data, sequential processing. |
| Dict | {"a": 1} |
Yes | Yes | Lookups, labeled data, representing rows. |
| Tuple | (1, 2) |
Yes | No | Fixed records, dict keys, function returns. |
Open your editor and build a simple portfolio tracker to combine these structures.
"ticker", "shares", and "price".sum() function on that new list to find the total portfolio value.portfolio = [
{"ticker": "AAPL", "shares": 10, "price": 150.0},
{"ticker": "MSFT", "shares": 5, "price": 310.0},
{"ticker": "GOOG", "shares": 2, "price": 2800.0}
]
# List comprehension extracting the value of each holding
values = [h["shares"] * h["price"] for h in portfolio]
total_value = sum(values)
print(f"Total Portfolio Value: ${total_value:,.2f}")