Skip to content

S2Q1 · Sum of Squares of Even Numbers

⚡ Quick Reference

Function: sum_of_squares_of_even(nums: list) -> int

Core idea: filter even numbers, square each one, sum them all.

def sum_of_squares_of_even(nums: list) -> int:
    return sum(x**2 for x in nums if x % 2 == 0)

Key rules: - Even → x % 2 == 0 - Square → x**2 - Sum everything matching the condition


Problem Statement

Problem

Write a function sum_of_squares_of_even(nums) that returns the sum of squares of all even numbers in nums.

Example:

Input
[1, 2, 3, 4, 5, 6]
Output
56

Even numbers: 2, 4, 6 → squares: 4, 16, 36 → sum: 56


Solution approaches

def sum_of_squares_of_even(nums: list) -> int:
    return sum(x**2 for x in nums if x % 2 == 0)
def sum_of_squares_of_even(nums: list) -> int:
    total = 0
    for x in nums:
        if x % 2 == 0:
            total += x ** 2
    return total
def sum_of_squares_of_even(nums: list) -> int:
    evens = filter(lambda x: x % 2 == 0, nums)
    return sum(map(lambda x: x**2, evens))

filter selects even numbers; map squares them; sum totals them. Clean functional pipeline.

def sum_of_squares_of_even(nums: list) -> int:
    return sum([x**2 for x in nums if x % 2 == 0])

Explicit list comprehension - same result as the generator but materialises the list in memory first. For large lists, the generator approach is more memory-efficient.

from functools import reduce

def sum_of_squares_of_even(nums: list) -> int:
    return reduce(lambda acc, x: acc + x**2 if x % 2 == 0 else acc, nums, 0)

reduce accumulates the sum directly - adds if x is even, leaves the accumulator unchanged otherwise.


Key takeaways

01

sum(x**2 for x in lst if cond)

The standard pattern for "filter then transform then sum". The condition goes inside the generator - no separate filter step needed.

02

Generator vs list comprehension

sum(x**2 for x in ...) uses a generator - values are computed one at a time without building a full list. sum([x**2 for x in ...]) builds the list first. For large inputs, generators use less memory.

03

filter + map + sum pipeline

Three separate operations chained together. Each function does one thing - filter selects, map transforms, sum aggregates. This separation of concerns makes each step independently readable.