💻 Module: 04-Data-Structures • Unabridged Executed Lesson
📑 Download Module Slides (PDF) 🐍 Download Notebook (.ipynb) 📊 ME200_Air_Ideal_Gas_Table.csv

Lesson 09: Python Data Structures — Lists, Tuples, Sets & Engineering Dictionaries

The “Boring Stuff” Problem: Organizing Hundreds of Materials, Nodes, and Fluids Without Chaos

Think about looking up steel yield strength \(S_y\), thermal conductivity \(k\), and density \(\rho\) at the back of three different textbooks—or keeping track of 20 sensor channels in variables named T1, T2, T3… all the way to T20! Whenever you see variables numbered 1, 2, 3..., stop—you need a Data Structure.

Python gives you four distinct containers, each built for a clear engineering job:

Container Syntax Ordered? Mutable? Mechanical Engineering Analogy
list [10.5, 20.1, 30.8] Yes Yes Lab data log you append measurements to
tuple (x_m, y_m, z_m) Yes No Fixed coordinate or reference fluid spec that must never shift
set {"316L", "6061-T6"} No Yes (unique!) Finding distinct alloy grades or deduplicating BOM part IDs
dict {"E_GPa": 200, "Sy_MPa": 250} Yes Yes Material Datasheet / Steam lookup table accessed by name, not row index!

Lists, List Comprehensions & the Dangerous Aliasing Gotcha (b = a)

Think of a Python list like a dynamic parts tray: .append(x) adds to the back, [-1] peeks at the newest entry, [start:stop] slices a window, and List Comprehensions [expr for x in seq if cond] transform whole lists in one crisp readable expression.

Watch Out! backup = pressures Does NOT Copy Your List!

In Python, variables are labels, not separate boxes. If you write backup = pressures and then modify pressures[0] = 999, backup[0] ALSO changes to 999 because both labels point to the exact same list object in memory! Always use backup = pressures.copy() (or copy.deepcopy() for nested dicts/lists).

# Example 1: Lists, Slicing, Comprehensions & Copy Protection
# Strain gauge readings [microstrain] along a composite wing spar
microstrains = [180, 420, 650, 910, 1180, 1490, 1720]
E_gpa = 72.0   # Al 7075-T6 [GPa]

# Safe copy before sorting or filtering!
baseline = microstrains.copy()
microstrains.append(1890)  # baseline stays unchanged at length 7!
print("Original baseline length:", len(baseline), "| Extended live tray length:", len(microstrains))

# List Comprehension: Convert all readings directly to Stress [MPa] where E[GPa]*eps[1e-6]*1000 = MPa
stresses_mpa = [round(E_gpa * (ue * 1e-6) * 1000.0, 2) for ue in microstrains]
critical_mpa = [s for s in stresses_mpa if s > 100.0]

print("All spar stresses [MPa] :", stresses_mpa)
print("High-stress zones >100  :", critical_mpa)

# Set deduplication for Bill of Materials (BOM) alloy audit
bom_parts = ["AISI-4140", "Al-6061", "AISI-4140", "316L-SS", "Al-6061", "Ti-6Al-4V"]
unique_alloys = sorted(set(bom_parts))
print(f"Total BOM entries: {len(bom_parts)} -> Distinct alloys to stock: {unique_alloys}")
Original baseline length: 7 | Extended live tray length: 8
All spar stresses [MPa] : [12.96, 30.24, 46.8, 65.52, 84.96, 107.28, 123.84, 136.08]
High-stress zones >100  : [107.28, 123.84, 136.08]
Total BOM entries: 6 -> Distinct alloys to stock: ['316L-SS', 'AISI-4140', 'Al-6061', 'Ti-6Al-4V']
# Example 2 (Materials Selection & HMT + Solids Cross-Reference): Ashby Dictionary Selector
# Dictionary mapping engineering alloys -> physical properties (rho [kg/m3], E [GPa], Sy [MPa], k [W/mK])
materials = {
    "AISI 1018 Steel": {"rho": 7870, "E_GPa": 205, "Sy_MPa": 370, "k_WmK": 51.9},
    "Al 6061-T6":      {"rho": 2700, "E_GPa": 69,  "Sy_MPa": 276, "k_WmK": 167.0},
    "Al 7075-T6":      {"rho": 2810, "E_GPa": 72,  "Sy_MPa": 503, "k_WmK": 130.0},
    "Ti-6Al-4V":       {"rho": 4430, "E_GPa": 114, "Sy_MPa": 880, "k_WmK": 6.7},
    "316L Stainless":  {"rho": 7990, "E_GPa": 193, "Sy_MPa": 290, "k_WmK": 16.2},
    "Copper C11000":   {"rho": 8940, "E_GPa": 117, "Sy_MPa": 220, "k_WmK": 391.0},
}

# Screen aerospace & thermal design metrics automatically across the entire database!
print(f"{'Alloy':<17} | {'Specific Yield (Sy/rho)':>23} | {'Stiffness Index sqrt(E)/rho':>27} | {'k [W/mK]':>8}")
print("-" * 84)
best_spec_str = ("", -1.0)
for name, p in materials.items():
    spec_strength = (p["Sy_MPa"] * 1e6) / p["rho"] / 1000.0   # kJ/kg (or kN*m/kg)
    stiff_idx = (p["E_GPa"] ** 0.5) / (p["rho"] / 1000.0)    # Beam minimum-weight index
    print(f"{name:<17} | {spec_strength:17.2f} kN*m/kg | {stiff_idx:27.3f} | {p['k_WmK']:8.1f}")
    if spec_strength > best_spec_str[1]:
        best_spec_str = (name, spec_strength)

print(f"\nHighest Specific Yield Strength -> {best_spec_str[0]} ({best_spec_str[1]:.1f} kN*m/kg)!")
Alloy             | Specific Yield (Sy/rho) | Stiffness Index sqrt(E)/rho | k [W/mK]
------------------------------------------------------------------------------------
AISI 1018 Steel   |             47.01 kN*m/kg |                       1.819 |     51.9
Al 6061-T6        |            102.22 kN*m/kg |                       3.077 |    167.0
Al 7075-T6        |            179.00 kN*m/kg |                       3.020 |    130.0
Ti-6Al-4V         |            198.65 kN*m/kg |                       2.410 |      6.7
316L Stainless    |             36.30 kN*m/kg |                       1.739 |     16.2
Copper C11000     |             24.61 kN*m/kg |                       1.210 |    391.0

Highest Specific Yield Strength -> Ti-6Al-4V (198.6 kN*m/kg)!

Notice how effortless dictionary lookups are compared to flipping through appendix pages: materials.get("Ti-6Al-4V", {}) safely checks existence without crashing with a KeyError, and nested dictionaries mimic real JSON engineering property databases!


Practice Questions (Concept Check)

  1. Why does changing copy_list[0] = 0 overwrite orig_list[0] if you wrote copy_list = orig_list?
  2. Why choose a tuple (x, y, z) for a fixed robot end-effector waypoint or thermodynamic reference datum instead of a list?
  3. What happens if you call materials["Inconel 718"] when "Inconel 718" is missing vs. calling materials.get("Inconel 718")?
  4. Write a 1-line list comprehension converting a list T_c_list = [20, 50, 100] to Kelvin.

Guided Practice Problem 1 (Worked Self-Check): Solar & Thermal Fluid Selection Table (Fluids + HMT)

Construct a dictionary htf_fluids storing water, engine oil, and glycol-water (rho, cp_J_kgK, k_W_mK, T_boil_C), filter ONLY fluids safe above \(120^\circ\text{C}\) operating collector temperature without boiling, and rank them by volumetric heat capacity \(\rho c_p\) (kJ/(m^3*K)).

Hint: Dict Comprehension + sorted(…, key=…, reverse=True)

Loop through htf_fluids.items(), keep fluids with props["T_boil_C"] > 120, and sort by rho * cp_J_kgK / 1000.0.

# Worked Practice Problem 1 Solution: Thermal Fluid Registry Selector
htf_fluids = {
    "Water (1 atm)":      {"rho": 997.0,  "cp": 4184.0, "T_boil_C": 100.0},
    "Water/Glycol 50/50": {"rho": 1065.0, "cp": 3450.0, "T_boil_C": 108.0},
    "Dowtherm A":         {"rho": 995.0,  "cp": 1820.0, "T_boil_C": 257.0},
    "Therminol VP-1":     {"rho": 1060.0, "cp": 1780.0, "T_boil_C": 257.0},
    "SAE 30 Engine Oil":  {"rho": 875.0,  "cp": 2050.0, "T_boil_C": 300.0},
}

T_op_C = 120.0
candidates = [
    (name, props["rho"] * props["cp"] / 1000.0, props["T_boil_C"])
    for name, props in htf_fluids.items()
    if props["T_boil_C"] > T_op_C + 10.0  # Require at least 10 C subcooling margin
]
candidates.sort(key=lambda item: item[1], reverse=True)

print(f"Viable Solar/HTF Fluids for T_op = {T_op_C} C:")
for name, vol_cp, tb in candidates:
    print(f"  - {name:<18s} | rho*cp = {vol_cp:7.1f} kJ/(m^3*K) | T_boil = {tb:.0f} C")
Viable Solar/HTF Fluids for T_op = 120.0 C:
  - Therminol VP-1     | rho*cp =  1886.8 kJ/(m^3*K) | T_boil = 257 C
  - Dowtherm A         | rho*cp =  1810.9 kJ/(m^3*K) | T_boil = 257 C
  - SAE 30 Engine Oil  | rho*cp =  1793.8 kJ/(m^3*K) | T_boil = 300 C

End-of-Chapter Practice Problems (Try Yourself!)

  1. Thermodynamic State Dictionary Builder (ME 200): Load the first 10 rows of datasets/ME200_Air_Ideal_Gas_Table.csv into a dictionary {T_K: (h_kJ_kg, u_kJ_kg, s_kJ_kgK)} and build a clean function querying u and h by Kelvin temperature (or printing available keys if absent).
  2. Pipe Fitting Loss Aggregator (Fluid Mechanics): Given a piping loop stored as a list of (fitting_name, K_L, count) tuples [("90-deg Elbow", 0.9, 6), ("Gate Valve Open", 0.2, 2), ("Tee Branch", 2.0, 1)], compute total minor loss coefficient \(\sum K_L\) and equivalent pressure loss at \(V = 2.8\text{ m/s}\).
  3. CAD Assembly Layer Audit (Sets): Compare req_bolts = {"M8-40", "M10-50", "M12-60"} against warehouse stock stock = {"M8-40", "M12-60", "M16-80"} using set difference (-) and intersection (&) to print missing fasteners immediately.

🎬 Concept & Engineering Animation

🎬 List Aliasing Vs Ashby Dict