List Comprehension

Yeeun·2025년 4월 16일

Python

목록 보기
5/31

🔁 Python Nested List Comprehension — Step-by-Step Guide (with Matrix Example)

When I first saw this line of Python code:

matrix = [[random.uniform(0, 1) for _ in range(cols)] for _ in range(rows)]

I got stuck.

I understood that the inner loop creates a list of random values between 0 and 1, but I couldn’t quite figure out how the outer loop works, and why it repeats the inner part.
If you're also confused about nested list comprehensions, this post is for you.

Let’s walk through it step by step with full explanations and examples.


🎯 What This Code Does

This line of code creates a 2D matrix (a list of lists), where:

  • rows is the number of rows
  • cols is the number of columns
  • Each value is a random float between 0 and 1
import random
matrix = [[random.uniform(0, 1) for _ in range(cols)] for _ in range(rows)]

✅ The Regular Way (Double For Loop)

Let’s break this down using regular loops:

matrix = []
for _ in range(rows):           # Outer loop (repeat for each row)
    row = []
    for _ in range(cols):       # Inner loop (fill each column)
        row.append(random.uniform(0, 1))
    matrix.append(row)

Example: rows = 2, cols = 3

[
  [0.41, 0.83, 0.22],
  [0.56, 0.91, 0.03]
]

Each row is a list of 3 random values, and the outer list contains 2 such rows.


✅ Equivalent List Comprehension

Now, let’s write the same logic using list comprehension:

matrix = [[random.uniform(0, 1) for _ in range(cols)] for _ in range(rows)]

Here’s how to read it:

  1. Outer loop:

    for _ in range(rows)

    → Repeat the inner logic for each row.

  2. Inner list comprehension:

    [random.uniform(0, 1) for _ in range(cols)]

    → Create one row of cols values.

  3. Final result: a list of rows.


💡 Why Does It Repeat?

You might be thinking:

"Wait, isn’t this inner list just a fixed list? How does the outer loop repeat it?"

That’s the key point!

❗️Each time the outer loop runs, it executes the inner list comprehension again, creating a new row.

So the result is not the same row copied multiple times.
It creates a new list of random values for each row.


✅ Alternative with Slightly Clearer Code

If the list comprehension still feels confusing, try this in between version:

matrix = []
for _ in range(rows):
    row = [random.uniform(0, 1) for _ in range(cols)]
    matrix.append(row)

This shows clearly that the inner list is built inside the outer loop.


📌 A Simpler Example

Let’s look at a simpler version that doesn’t use random, just to understand the shape:

[[x for x in range(3)] for _ in range(2)]

Output:

[[0, 1, 2], [0, 1, 2]]

What happened here?

  • The inner loop creates [0, 1, 2]
  • The outer loop repeats it twice → 2 rows of [0, 1, 2]

This helps visualize what nested list comprehensions are doing.


🧠 General Format

Here’s a template for how nested list comprehensions work:

outer_list = [inner_list for outer_var in outer_iterable]

And the inner_list can also be a list comprehension:

inner_list = [expression for inner_var in inner_iterable]

Putting them together:

[[expression for inner_var in inner_iterable] for outer_var in outer_iterable]

✅ Summary

  • The outer loop creates multiple rows
  • The inner loop fills one row
  • List comprehension nests loops from inside → out, just like regular loops
  • Each time the outer loop runs, it runs the inner list comprehension again

🙋🏻 Final Tip

If you're ever confused, write it out using normal for loops first — then convert to list comprehension.
It’s not cheating — it’s smart.


Let me know if you want more beginner-friendly Python breakdowns! 🐍💡

0개의 댓글