Predict the Output: if vs if-else
Intermediate · Predict the output · 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 lessonRead this code carefully and predict what it will print. Pay attention to where the if-else is placed.
Type the exact output.
nums = [1, 2, 3, 4, 5]
result = ['even' if n % 2 == 0 else 'odd' for n in nums]
print(result)
More Comprehensions exercises
- Double Every NumberBeginner
- Filter Even NumbersBeginner
- Create a Dict ComprehensionIntermediate
- Unique Vowels with a Set ComprehensionIntermediate
- Fix the Bug: Wrong Comprehension SyntaxIntermediate
- Refactor a Loop into a ComprehensionIntermediate
- Flatten a MatrixAdvanced
All Python exercises · 50 practice problems · Data Structures quiz