Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
When engineering applications that handle tabular records, image pixel arrays, geographical coordinates, or hierarchical JSON datasets, you constantly work with nested data structures.
A Nested Comprehension is a comprehension contained inside another comprehension. It allows you to generate multi-dimensional grids, transpose matrices, and transform deeply nested dictionaries in declarative, high-speed Python.
Imagine the reservation chart for an Indian Railways 3-Tier AC coach (B1):
+-------------------------------------------------------------------------+ | RAILWAY COACH BERTH MATRIX GENERATOR | +-------------------------------------------------------------------------+ | | | Outer Comprehension: [ Coach Compartments 1 to 8 ] | | │ | | ▼ | | Inner Comprehension: [ Berths inside Compartment: Lower, Middle, Upper]| | │ | | ▼ | | Resulting 2D Structure: | | [ | | ["Bay 1 - Lower", "Bay 1 - Middle", "Bay 1 - Upper"], | | ["Bay 2 - Lower", "Bay 2 - Middle", "Bay 2 - Upper"], | | ... | | ] | +-------------------------------------------------------------------------+
Developers often confuse two completely different syntax patterns:
+------------------------------------+------------------------------------+ | 1. Flattening Comprehension | 2. True Nested Comprehension | | (Results in 1D flat list) | (Results in 2D nested list) | +------------------------------------+------------------------------------+ | [val for row in grid for val in r]| [[val for val in row] for row in g| | | | | Output: [1, 2, 3, 4] | Output: [[1, 2], [3, 4]] | +------------------------------------+------------------------------------+
[x for sublist in list for x in sublist]):The loops read left-to-right exactly like nested for statements: outer first, inner second.
[[expr for inner] for outer]):The outer comprehension runs the outer loop, and its expression is an entire enclosed inner comprehension.
Expected Output:
Transposing a matrix swaps rows into columns ($M_{ij} \to M_{ji}$). This is a fundamental operation in numerical computing and data analysis.
Expected Output:
Hierarchical corporate structures often store departments, employees, and salaries. Nested dictionary comprehensions transform multi-tier mappings effortlessly:
Expected Output:
Expected Output:
While Python allows arbitrary nesting, deeply nested comprehensions quickly become unreadable write-only code (often termed "comprehension pyramids").
for loops. Readability always counts more than terseness.| Practice | Bad / Unreadable Pattern | Recommended Gold Standard |
|---|---|---|
| Grid Generation | [[x for x in r] for r in [[y for y in z] for z in w]] (3+ levels) | Max 2 levels; refactor deeper levels into generator functions |
| Transposition | Manual indexed nested loops with temporary arrays | [[row[i] for row in matrix] for i in range(cols)] |
| Flattening Syntax | Putting inner loop before outer loop (causes SyntaxError) | Order for loops left-to-right matching standard nested loop order |
| Formatting | Writing nested comprehensions on one giant 150-char line | Format across multiple indented lines for visual hierarchy |
[[f(x, y) for y in col_iter] for x in row_iter][item for sublist in matrix for item in sublist][[row[i] for row in matrix] for i in range(len(matrix[0]))]{outer_k: {inner_k: expr for inner_k, v in inner_d.items()} for outer_k, inner_d in d.items()}In Indian Railways Sleeper coaches, each compartment bay contains 6 berths numbered across 3 tiers:
n % 3 == 1n % 3 == 2n % 3 == 0Given 3 consecutive bays with seat numbers 1 to 18:
"LB", "MB", or "UB").In the next lesson, we will continue your intermediate Python journey with Project: Data Filtering with Comprehensions (1: Advanced Data Types & Comprehensions).
👉 Continue to Next Lesson: Project: Data Filtering with Comprehensions →
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Dictionary Comprehensions | Advanced Structural Pattern Matching with Guards and Class Patterns |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.