How to Filter Even Numbers and Square Them in Python

Create two beginner-friendly helper functions that filter even numbers and compute squares of a number list using loops, then print the results along with the sum and average.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 15 views 0 copies

Python code

23 lines
Python 3.9+
def get_even_numbers(numbers):
    evens = []
    for num in numbers:
        if num % 2 == 0:
            evens.append(num)
    return evens

def get_squares(numbers):
    squares = []
    for num in numbers:
        squares.append(num ** 2)
    return squares

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_numbers = get_even_numbers(numbers)
squares = get_squares(numbers)

print(f"Numbers: {numbers}")
print(f"Even numbers: {even_numbers}")
print(f"Squares: {squares}")
print(f"Total sum: {sum(numbers)}")
print(f"Average: {sum(numbers) / len(numbers)}")

Output

stdout
Numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Even numbers: [2, 4, 6, 8, 10]
Squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Total sum: 55
Average: 5.5

How it works

This script defines two reusable functions that iterate through a list. get_even_numbers uses the modulo operator % to check if a number is divisible by 2 before appending it to a new list. get_squares computes each number's square with num ** 2 and stores it. After building the helpers, the code collects the transformed lists and prints them. The sum() function totals the list, and dividing by len() gives the average. Building small loops like these teaches how to accumulate results into a new list and makes data transforms clear and readable.

Common mistakes

  • Using `num / 2` instead of `num % 2` for even detection, which gives a float not a remainder.
  • Forgetting to initialize the result list before the loop, leading to a NameError.
  • Appending inside an `if` without proper indentation, causing logic errors or a syntax error.

Variations

  1. Use a list comprehension: `[num for num in numbers if num % 2 == 0]` for filtering evens.
  2. Use the `map()` function with a lambda to compute squares: `list(map(lambda x: x**2, numbers))`.

Real-world use cases

  • Filtering user-input IDs where only even-numbered records need processing.
  • Computing squared distances or areas for geometry calculations in a data pipeline.
  • Summarizing numeric sensor readings by filtering outliers and calculating averages.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.