← Back to Blog

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() and int()
  • 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.

[ login to bookmark ] // copied! 18 views · 1 min
// resources
Exercise even_numbers_2.py
← prev Building Dicts the Short Way next → Files: Where Your Data Lives After the Program Stops
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.