Lesson 13: Lists, Slicing, Comprehensions & The List-Copying Trap (copy())

The β€œBoring Stuff” Problem: Scrubbing -200 Sensor Faults Without Corrupting Raw Archives

Real air sensors (UCI_Air_Quality_Italy_Hourly.csv) insert -200 whenever a probe reboots or drifts off-calibration. If you want a filtered list of valid measurements while preserving the raw archive for QA auditing:

Watch Out! Mutable Aliasing (backup = readings Does NOT Copy!)

In Python, writing filtered = raw_readings attaches TWO names to the exact same list in RAM! Calling filtered.sort() or filtered[0] = 0.0 silently mutates raw_readings too! Always copy lists cleanly via raw_readings.copy() or slicing raw_readings[:].

from pathlib import Path
def data_file(name):
    """Locate a dataset file whether running from SRC_DIR, module folder, HOMEWORK, or EXAMS."""
    for p in [
        Path("datasets") / name,
        Path("../datasets") / name,
        Path("../../datasets") / name,
    ]:
        if p.exists():
            return p
    raise FileNotFoundError(f"Missing dataset {name} in datasets/")
import csv

# Example 1 (Real UCI Data Cleaning): Filtering -200 Fault Flags from Benzene C6H6 Readings
with data_file("UCI_Air_Quality_Italy_Hourly.csv").open(encoding="utf-8", newline="") as f:
    reader = csv.reader(f, delimiter=";")
    header = next(reader)
    c6h6_raw = [float(row[5].replace(",", ".")) for row in reader if len(row) > 5 and row[5].strip()]

# List comprehension cleanly isolates valid hours (> -199) WITHOUT altering c6h6_raw!
c6h6_valid = [val for val in c6h6_raw if val > -199.0]
invalid_count = len(c6h6_raw) - len(c6h6_valid)

# Preserve order in c6h6_valid while sorting a COPY to find peak urban benzene hours
sorted_c6h6 = sorted(c6h6_valid, reverse=True)
print("=== UCI Italy Air Quality β€” Benzene (C6H6) List Audit ===")
print(f"Total Hourly Rows : {len(c6h6_raw)} | Fault (-200) Count : {invalid_count} ({invalid_count/len(c6h6_raw):.1%})")
print(f"Valid Mean C6H6   : {sum(c6h6_valid)/len(c6h6_valid):.2f} ug/m^3 | Top-5 Peak Hours [ug/m^3]: {sorted_c6h6[:5]}")
print(f"Raw First 3 Still Intact (Aliasing Avoided): {c6h6_raw[:3]}")
=== UCI Italy Air Quality β€” Benzene (C6H6) List Audit ===
Total Hourly Rows : 9357 | Fault (-200) Count : 366 (3.9%)
Valid Mean C6H6   : 10.08 ug/m^3 | Top-5 Peak Hours [ug/m^3]: [63.7, 52.1, 50.8, 50.7, 50.6]
Raw First 3 Still Intact (Aliasing Avoided): [11.9, 9.4, 9.0]
# Example 2: Demonstrating Aliasing Bug vs Safe .copy()
sensor_orig = [12.4, -200.0, 15.1]
alias_bug = sensor_orig        # WRONG! Same list object
safe_clone = sensor_orig.copy()
alias_bug[1] = 0.0             # Corrupts sensor_orig too!
print("After mutating alias_bug -> sensor_orig =", sensor_orig, "| safe_clone =", safe_clone)
After mutating alias_bug -> sensor_orig = [12.4, 0.0, 15.1] | safe_clone = [12.4, -200.0, 15.1]

Concept Check Questions

  1. Explain in your own words why safe_clone = sensor_orig.copy() protects original QA records whereas alias_bug = sensor_orig does not.
  2. What does sorted_c6h6[-5:] return on a descending sorted list?
  3. Convert this 4-line loop into a 1-line list comprehension: filter pm_list for strictly valid readings > 0.0.

Guided Practice Problem 1: Winter Beijing PM2.5 Top-10 Extreme Hours (UCI_Beijing_PM25_Meteorology.csv)

Using csv.DictReader, extract valid numeric pm2.5 readings (skip "NA"!) specifically during month == "1" (January) across 2010–2014, compute the January mean \(\text{PM}_{2.5}\), count how many January hours exceeded \(150\,\mu\text{g/m}^3\), and print the top 5 hourly peaks.

# Guided Practice 1 Starter
with data_file("UCI_Beijing_PM25_Meteorology.csv").open(encoding="utf-8", newline="") as f:
    jan_pm = [float(r["pm2.5"]) for r in csv.DictReader(f) if r["month"] == "1" and r["pm2.5"] != "NA"]
above_150 = [x for x in jan_pm if x > 150.0]
print(f"Jan Valid Hours: {len(jan_pm)} | Mean PM2.5: {sum(jan_pm)/len(jan_pm):.1f} ug/m^3 | Hours >150: {len(above_150)} ({len(above_150)/len(jan_pm):.1%})")
print("Top 5 Jan Peaks [ug/m^3]:", sorted(jan_pm, reverse=True)[:5])
Jan Valid Hours: 3471 | Mean PM2.5: 115.1 ug/m^3 | Hours >150: 928 (26.7%)
Top 5 Jan Peaks [ug/m^3]: [994.0, 972.0, 886.0, 858.0, 852.0]