Editor

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 lesson

Read 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

All Python exercises · 50 practice problems · Data Structures quiz