Refactor a Loop into a Comprehension
Intermediate · Refactor · 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 lessonRefactor the following loop into a single list comprehension. The output must stay exactly the same.
Expected output:
[1, 9, 25, 49, 81]numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = []
for n in numbers:
if n % 2 != 0:
result.append(n ** 2)
print(result)
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
- Flatten a MatrixAdvanced
All Python exercises · 50 practice problems · Data Structures quiz