// Data Structures
Comprehensions Mini Project — Even Numbers
What you're building
The even numbers filter is back. Same input, same output — but the function is now one line.
This is what comprehensions are for: replacing a loop-and-append pattern with a single expression.
What you need to know first
- List comprehensions
- Functions — defining, parameters, return
input()andint()- The modulo operator
%
The original
This is what you wrote before:
def get_even(numbers):
even = []
for num in numbers:
if num % 2 == 0:
even.append(num)
return even
The brief
Rewrite get_even() using a list comprehension.
Everything else stays the same — input collection, output, printed result.
Think before you code
- What is the expression in the comprehension?
- What is the condition?
- What does the function return?
Expected output
Number 1: 4
Number 2: 7
Number 3: 12
Number 4: 3
Number 5: 8
Number 6: 15
All numbers: [4, 7, 12, 3, 8, 15]
Even numbers: [4, 12, 8]
The solution
def get_even(numbers):
return [num for num in numbers if num % 2 == 0]
numbers = []
for i in range(6):
num = int(input(f"Number {i + 1}: "))
numbers.append(num)
even = get_even(numbers)
print(f"\nAll numbers: {numbers}")
print(f"Even numbers: {even}")
Four lines became one. The logic is identical — the comprehension just says it shorter.
// resources
// 0 comments
// No comments yet. Be the first.
// leave a comment