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 lessonUse 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]
45matrix = [[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
- Double Every NumberBeginner
- Filter Even NumbersBeginner
- Predict the Output: if vs if-elseIntermediate
- Create a Dict ComprehensionIntermediate
- Unique Vowels with a Set ComprehensionIntermediate
- Fix the Bug: Wrong Comprehension SyntaxIntermediate
- Refactor a Loop into a ComprehensionIntermediate
All Python exercises · 50 practice problems · Data Structures quiz