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.
This line of code creates a 2D matrix (a list of lists), where:
rows is the number of rowscols is the number of columns0 and 1import random
matrix = [[random.uniform(0, 1) for _ in range(cols)] for _ in range(rows)]
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)
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.
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:
Outer loop:
for _ in range(rows)
→ Repeat the inner logic for each row.
Inner list comprehension:
[random.uniform(0, 1) for _ in range(cols)]
→ Create one row of cols values.
Final result: a list of rows.
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.
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.
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)]
[[0, 1, 2], [0, 1, 2]]
What happened here?
[0, 1, 2] [0, 1, 2]This helps visualize what nested list comprehensions are doing.
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]
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! 🐍💡