FAI Study Hub
← Back to Study Hub
Module 05 · Python & Pandas
← Hub
Intuition Memory id() Pandas Cleaning Matplotlib Traps Past Papers Slicing Tool Quiz Checklist
Module 05 · Programmatic Foundations & Data Analysis

Python Core, Pandas & Visualization

Master Python internals and statistical data wrangling. Complete verified solutions for Mutability vs Immutability with memory `id()` demonstrations, recursive factorial $n!$, Pandas missing value imputation, group-by aggregations, and publication-ready Matplotlib visualizations.

May 2025 (Q1 20M, Q2 20M) Nov 2025 (Q1 20M, Q2 20M) Memory id() Proof Pandas Cleaning Matplotlib / Seaborn

01. Intuition & Concept Contrast

Python treats everything as an object in memory. Understanding the distinction between mutable references and immutable values is critical for algorithm safety and memory optimization.

Memory Behavior

Mutable vs Immutable Objects

Mutable Objects (`list`, `dict`, `set`): State can be changed in place without changing memory address (`id()`). Unhashable; cannot be used as dictionary keys.

Immutable Objects (`int`, `float`, `str`, `tuple`): State cannot be modified once instantiated. Any alteration spawns a brand-new object at a new memory address. Hashable.

Data Manipulation

Python Loops vs Vectorized Pandas

Standard Python Loops: Iterates row by row in bytecode; slow for large datasets ($O(n)$ with high interpreter overhead).

Vectorized Pandas/NumPy: Operates on contiguous memory blocks compiled in C; orders of magnitude faster.

02. Mutability & Memory Identity Proof

Nov 2025 (Q1.a) & May 2025 (Q1.i) Core 5-10 Mark Question.

1. Is String a Mutable Data Type?

No, strings in Python are strictly immutable. Attempting in-place item assignment (`s[0] = 'H'`) raises a `TypeError: 'str' object does not support item assignment`.

2. Empirical Code Demonstration for Exam Booklet:

# Mutable Demonstration (List)
numbers = [1, 2, 3]
addr_before = id(numbers)
numbers.append(4)  # Modifies in-place
print(id(numbers) == addr_before)  # True: Memory address remains identical!

# Immutable Demonstration (String)
message = "Hello"
addr_initial = id(message)
message += " World"  # Spawns a brand-new string object
print(id(message) != addr_initial)  # True: Memory address changed!

3. Recursive Factorial Formulation:

$$n! = \begin{cases} 1, & \text{if } n \in \{0, 1\} \quad (\text{Base Case}) \\ n \times (n - 1)!, & \text{if } n > 1 \quad (\text{Recursive Step}) \end{cases}$$
def factorial(n: int) -> int:
    """Computes factorial of non-negative integer using recursion."""
    if n < 0:
        raise ValueError("Factorial is undefined for negative integers.")
    if n in (0, 1):
        return 1
    return n * factorial(n - 1)

03. Pandas Data Cleaning & Exploratory Data Analysis (EDA)

May 2025 (Q2) & Nov 2025 (Q2) Guaranteed 15-20 Mark Problem.

Operation Pandas Method Exam Code Pattern
Load Dataset `pd.read_csv()` `df = pd.read_csv("sales_data.csv")`
Detect Missing Values `isna().sum()` `df.isnull().sum()`
Impute Missing Values `fillna()` `df["Sales"].fillna(df["Sales"].mean(), inplace=True)`
Drop Missing Rows `dropna()` `df.dropna(subset=["Product"], inplace=True)`
Group-By Aggregations `groupby().agg()` `df.groupby("Store")["Sales"].agg(["sum", "mean"])`
Filtering & Boolean Index `df[...]` `df[(df["Category"] == "Electronics") & (df["Total_Sales"] > 10000)]`
Top N Highest Rows `nlargest()` / `sort_values()` `df.sort_values(by="Total_Sales", ascending=False).head(5)`

04. Matplotlib Chart Customization

Creating customized publication-ready charts with axis labels, titles, and color palettes.

import matplotlib.pyplot as plt

# 1. Bar Plot of Top 5 Products by Sales
plt.figure(figsize=(8, 5))
plt.bar(top5["Product_Name"], top5["Total_Sales"], color="#2563eb", edgecolor="black")
plt.title("Top 5 Products by Total Sales", fontsize=14, fontweight="bold")
plt.xlabel("Product Name", fontsize=12)
plt.ylabel("Total Sales (USD)", fontsize=12)
plt.xticks(rotation=25)
plt.grid(axis="y", linestyle="--", alpha=0.7)
plt.tight_layout()
plt.show()

# 2. Score Distribution Histogram
plt.figure(figsize=(7, 4))
plt.hist(df["Marks_Math"], bins=5, color="#059669", edgecolor="white")
plt.title("Mathematics Score Distribution", fontsize=14)
plt.xlabel("Marks Range", fontsize=12)
plt.ylabel("Student Count", fontsize=12)
plt.tight_layout()
plt.show()

05. Notation & Complexity Matrix

Operation Data Type Time Complexity Space Complexity
`list.append(x)` List (Mutable) $O(1)$ amortized $O(1)$
`list.insert(0, x)` List (Mutable) $O(n)$ (Shifts all elements) $O(1)$
`dict[key]` lookup Dictionary (Hash table) $O(1)$ average $O(1)$
`str[i:j:k]` String (Immutable) $O(k)$ (Copies sub-string) $O(k)$ new object created
`df.groupby()` DataFrame $O(n)$ hash / sort $O(n)$

06. Repeatable Step-by-Step Solving Protocol

Step 1: Check Data Immutability Rules

State clearly that strings, tuples, and numbers are immutable; lists, sets, and dictionaries are mutable.

Step 2: Inspect Missing Data (`NaN`)

Calculate missing values per column with `df.isnull().sum()`. Choose appropriate remediation (mean imputation for continuous, dropna for categorical labels).

Step 3: Execute Group-by Aggregations

Specify aggregation functions explicitly: `df.groupby('Gender').mean(numeric_only=True)`.

Step 4: Format Matplotlib Code Completely

Always write `plt.title()`, `plt.xlabel()`, `plt.ylabel()`, `plt.grid()`, and `plt.show()`.

07. 6 Deadly Exam Traps & Common Student Mistakes

Trap 01: In-Place Mutation of Strings

Writing `s[0] = 'H'`

Strings are immutable in Python. Writing `s[0] = 'H'` raises a `TypeError`. You must create a new slice: `s = 'H' + s[1:]`.

Trap 02: Forgetting Inplace in Pandas

Writing `df.dropna()` Without Saving Result

`df.dropna()` returns a copy by default. You must write `df = df.dropna()` or `df.dropna(inplace=True)`.

Trap 03: Negative Number Factorial

Missing $n < 0$ Guard in Recursion

If a student passes negative numbers, unprotected factorial recurses infinitely until `RecursionError: maximum recursion depth exceeded`. Always raise `ValueError` for $n < 0$.

Trap 04: Strict Inequality Filter

Confusing `> 10000` with `>= 10000`

In May 2025, Laptop has total sales of exactly $10,000$. Strict inequality `> 10000` returns zero rows; `>= 10000` includes Laptop. Explicitly point out this distinction to the examiner.

Trap 05: Categorical vs Numerical Misclassification

Treating `Product_ID` as Numerical

Even though an ID contains numbers, mathematical operations (mean, sum) are meaningless on it. `Product_ID` is **Categorical / Nominal**, not numerical.

Trap 06: Missing Axis Labels in Plotting

Drawing Plots Without Labels

Examiners automatically deduct 3 to 4 marks if `xlabel`, `ylabel`, and `title` are omitted from Matplotlib code.

08. Complete University Question Bank (All Past PYQs Solved)

Nov 2025 · Question 1 Mutability, Recursive Factorial & List Processing (20 Marks)
Question Statement:
a) Differentiate between mutable and immutable data types in Python with examples. (5 Marks)
b) Write a Python program to find the factorial of a number using recursion. (5 Marks)
c) Write a Python program to input n numbers into a list and find sum, average, min, max, and sort ascending/descending. (10 Marks)

Solution:

a) Mutable vs. Immutable Comparison (5 Marks):
DimensionMutable Types (`list`, `dict`, `set`)Immutable Types (`str`, `int`, `tuple`)
In-Place ModificationSupported (memory address `id()` is preserved)Not supported (spawns brand-new object in memory)
Dictionary KeysCannot be keys (unhashable)Can be dictionary keys (hashable)
Example Verification`a = [1]; addr = id(a); a.append(2); assert id(a) == addr``s = 'a'; addr = id(s); s += 'b'; assert id(s) != addr`
b) Recursive Factorial Program (5 Marks):
def factorial(n: int) -> int:
    if n < 0:
        raise ValueError("Factorial is undefined for negative integers.")
    if n in (0, 1):
        return 1
    return n * factorial(n - 1)

print(factorial(5))  # Output: 120
c) List Processing Program (10 Marks):
def process_numbers():
    n = int(input("Enter count: "))
    nums = [float(input(f"Enter element {i+1}: ")) for i in range(n)]
    
    total_sum = sum(nums)
    avg = total_sum / n
    max_val = max(nums)
    min_val = min(nums)
    asc = sorted(nums)
    desc = sorted(nums, reverse=True)
    
    print(f"Sum: {total_sum}, Average: {avg:.2f}")
    print(f"Min: {min_val}, Max: {max_val}")
    print(f"Ascending: {asc}")
    print(f"Descending: {desc}")
May 2025 · Question 2 Pandas Data Cleaning, GroupBy & Matplotlib Customization (20 Marks)
Question Statement:
Demonstrate loading a dataset into Pandas, cleaning data (handling missing values, dropping columns), group-by operations, calculating summary statistics, and creating customized line, bar, and scatter plots using Matplotlib. (20 Marks)

Solution:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 1. Load Dataset
df = pd.read_csv("store_sales.csv")

# 2. Data Cleaning
# Impute numeric missing values with median
df["Sales"].fillna(df["Sales"].median(), inplace=True)
# Drop rows where Product is NaN
df.dropna(subset=["Product"], inplace=True)
# Drop unneeded columns
df.drop(columns=["Unneeded_Col"], inplace=True, errors="ignore")

# 3. Summary Statistics & First 10 Rows
print(df.head(10))
print(df.describe())

# 4. GroupBy Aggregations
store_perf = df.groupby("Store").agg({
    "Sales": ["sum", "mean"],
    "Quantity": "sum"
})
print(store_perf)

# 5. Visualization Suite
plt.figure(figsize=(10, 4))

# Bar Plot
plt.subplot(1, 2, 1)
store_totals = df.groupby("Store")["Sales"].sum()
plt.bar(store_totals.index, store_totals.values, color="#2563eb", edgecolor="black")
plt.title("Total Sales by Store", fontweight="bold")
plt.xlabel("Store Name")
plt.ylabel("Sales ($)")

# Scatter Plot
plt.subplot(1, 2, 2)
plt.scatter(df["Quantity"], df["Sales"], color="#dc2626", alpha=0.7)
plt.title("Quantity vs Sales Correlation", fontweight="bold")
plt.xlabel("Quantity Sold")
plt.ylabel("Sales ($)")

plt.tight_layout()
plt.show()

09. Interactive Offline Python String Slicing Sandbox

Test your understanding of Python slicing `string[start:stop:step]` directly in the browser.

Click button to test slicing.

10. Active Recall Self-Test Quiz

Answer the questions below to evaluate progress (0/4 answered).
1. What happens if you execute `s = "Hello"; s[0] = "h"` in Python?
Correct: (b) Strings in Python are strictly immutable; characters cannot be reassigned in place.
2. Which built-in function reveals the unique memory address identity of a Python object?
Correct: (c) `id(obj)` returns the integer memory address of the object in CPython.
3. In Pandas, what is the default behavior of `df.dropna()` if `inplace=True` is omitted?
Correct: (b) By default, `dropna()` returns a copy. To modify in place, pass `inplace=True` or reassign `df = df.dropna()`.
4. Why is a column like `Product_ID` (e.g. "P001", "P002") classified as categorical rather than numerical?
Correct: (c) IDs are categorical identifiers (nominal scale). Computing an average ID is mathematically meaningless.

11. Exam Hall Answer Sheet Presentation Checklist

1. Define Mutability with `id()` Code Proof

Show that `id(list)` stays identical after append, while `id(str)` changes after concatenation.

2. For Recursion, Show Both Base Case & Negative Guard

Always write `if n < 0: raise ValueError` and `if n in (0, 1): return 1`.

3. In Pandas, Distinguish Imputation vs Dropping

Explain when to use `fillna(df['col'].mean())` vs `dropna(subset=['target'])`.

4. Provide All 3 Chart Elements in Matplotlib

Always include `plt.title()`, `plt.xlabel()`, `plt.ylabel()`, and `plt.show()`.