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.
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.
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.
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
State clearly that strings, tuples, and numbers are immutable; lists, sets, and dictionaries are mutable.
Calculate missing values per column with `df.isnull().sum()`. Choose appropriate remediation (mean imputation for continuous, dropna for categorical labels).
Specify aggregation functions explicitly: `df.groupby('Gender').mean(numeric_only=True)`.
Always write `plt.title()`, `plt.xlabel()`, `plt.ylabel()`, `plt.grid()`, and `plt.show()`.
07. 6 Deadly Exam Traps & Common Student Mistakes
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:]`.
Writing `df.dropna()` Without Saving Result
`df.dropna()` returns a copy by default. You must write `df = df.dropna()` or `df.dropna(inplace=True)`.
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$.
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.
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.
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)
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):
| Dimension | Mutable Types (`list`, `dict`, `set`) | Immutable Types (`str`, `int`, `tuple`) |
|---|---|---|
| In-Place Modification | Supported (memory address `id()` is preserved) | Not supported (spawns brand-new object in memory) |
| Dictionary Keys | Cannot 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: 120c) 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)
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.
10. Active Recall Self-Test Quiz
11. Exam Hall Answer Sheet Presentation Checklist
Show that `id(list)` stays identical after append, while `id(str)` changes after concatenation.
Always write `if n < 0: raise ValueError` and `if n in (0, 1): return 1`.
Explain when to use `fillna(df['col'].mean())` vs `dropna(subset=['target'])`.
Always include `plt.title()`, `plt.xlabel()`, `plt.ylabel()`, and `plt.show()`.