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.
Python code
23 linesdef 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
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
- Use a list comprehension: `[num for num in numbers if num % 2 == 0]` for filtering evens.
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.