BudiBadu Logo

Filter and Square Even Numbers

Python Easy 7 views

Practice Python list comprehensions as a concise and expressive way to process sequences. You will work with a list of integers and use a single list comprehension to both filter values based on a condition and transform them into the desired form, instead of writing multiple loops and temporary lists.

The task is to design a list comprehension that reads the input list, keeps only the elements that meet the required criteria, and applies the correct transformation before building the final result list. Focus on writing a clear, readable expression that makes the filtering condition and the transformation step easy to understand at a glance.

Example 1:

Input: numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Output: [4, 16, 36, 64, 100]
Explanation: Filter even numbers (2, 4, 6, 8, 10) and square them.

Example 2:

Input: numbers = [2, 4, 6, 8]
Output: [16, 64]
Explanation: Filter even numbers, square them, keep only values greater than 10.

Example 3:

Input: numbers = [1, 3, 5, 7, 9]
Output: []
Explanation: No even numbers found, return empty list.

Algorithm Flow

Recommendation Algorithm Flow for Filter and Square Even Numbers - Budibadu
Recommendation Algorithm Flow for Filter and Square Even Numbers - Budibadu

Best Answers

python - Approach 1
def filter_and_square_even(numbers):
    return [n * n for n in numbers if n % 2 == 0]