Editor

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 lesson

This 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

All Python exercises · 50 practice problems · Data Structures quiz