BudiBadu Logo

Filter and Square Even Numbers

Python Easy 12 views
Like3

In Filter and Square Even Numbers for Python, you get a list of integers and need to build a new list that keeps only even values, then squares each kept value. Keep the original order from left to right. Odd numbers are skipped completely, and valid even numbers include 0 and negative values before squaring.

The judge calls filter_and_square_even(nums) and checks the returned list exactly, so correctness is about content and order, not print output. For example, inputs with only odd numbers should return an empty list, while mixed inputs should return only squared even entries. If the input contains -2 and -4, the output should include 4 and 16.

A clean Python approach is a list comprehension that combines filtering and transformation in one readable expression. Keep the solution deterministic and side-effect free. Do not return strings or tuples; return a plain Python list of integers so it matches the expected answer format used by the test harness in all official checks.

Examples

Example 1
Input
[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
[2, 4, 6, 8]
Output
[16, 64]
Explanation

Filter even numbers (2, 4, 6, 8) and square them.

Example 3
Input
[1, 3, 5, 7, 9]
Output
[]
Explanation

No even numbers, so 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]