Editor

Flatten a Matrix

Advanced · Write the code · from Python Comprehensions: List, Dict, Set, and Generator in One Guide

From the lesson: Python Comprehensions: List, Dict, Set, and Generator in One Guide

Imagine you have a list of 100 numbers and you want a new list containing only the even ones, each doubled. With a regular loop, that takes four lines. With a Python comprehension, it takes one.

Read the lesson

Use a list comprehension with two for clauses to flatten the given matrix (a list of lists) into a single flat list. Then print the sum of all items using a generator expression inside sum().

Expected output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
45
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Flatten using a list comprehension with nested for clauses
# Print the flat list
# Print the sum using a generator expression

More Comprehensions exercises

All Python exercises · 50 practice problems · Data Structures quiz