Filter Even Numbers
Beginner · Write the code · 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 lessonUse a list comprehension with an if clause to create a list called evens that contains only the even numbers from the given list.
Expected output:
[4, 12, 8, 20, 6]numbers = [3, 4, 7, 12, 8, 15, 20, 6, 9]
# Create evens using a list comprehension with filtering
print(evens)
More Comprehensions exercises
- Double Every NumberBeginner
- Predict the Output: if vs if-elseIntermediate
- 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