Fix the Bug: Wrong Comprehension Syntax
Intermediate · Fix the bug · 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 lessonThis code tries to create a list where numbers above 5 are labeled 'high' and others are labeled 'low'. But the syntax is wrong and it crashes. Fix it.
Expected output:
['low', 'high', 'low', 'high', 'low', 'high']nums = [3, 8, 2, 9, 1, 7]
result = ['high' for n in nums if n > 5 else 'low']
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
- Refactor a Loop into a ComprehensionIntermediate
- Flatten a MatrixAdvanced
All Python exercises · 50 practice problems · Data Structures quiz