Lesson 02 · foundations

Lists, Dicts & Tuples

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.

1. Lists: Ordered & Mutable

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]
Note A pandas Series (a single column of data) is essentially a highly-optimized, labeled list.

2. Dictionaries: Key-Value Pairs

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()}
Note Think of a pandas DataFrame as a dictionary where keys are column names, and values are lists of data. A single DataFrame row being extracted often looks exactly like a dict.

3. Tuples: Immutable Sequences

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.

Note When you iterate over DataFrame rows using .iterrows(), pandas returns each row as a tuple of (index, Series). DataFrame index entries themselves are also built on tuples.

Comparison

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.

Do this now

Open your editor and build a simple portfolio tracker to combine these structures.

  1. Create a list of dictionaries. Each dictionary should represent a holding with keys: "ticker", "shares", and "price".
  2. Use a list comprehension to calculate the total value of each holding (shares × price).
  3. Use the built-in sum() function on that new list to find the total portfolio value.
  4. Print the result.
Stuck? View a solution
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}")
Win You now understand lists, dicts, and tuples—the structural glue of Python. When you start pulling in raw data, it usually lands in these formats before pandas even touches it!

Go deeper