Quick Overview
`[n for n in range(x) if n % 2 == 0]` materialises the entire list in memory. Swapping the brackets for parentheses gives a generator that produces each value only when asked.
Create a function find_even_nums(n) that takes an integer n and returns a list of all even numbers from 1 up to and including n.
Sequence generation paired with filtering forms the backbone of numerical algorithms, batch processing, and pagination steps.
Use a list comprehension with a range(2, n + 1, 2) step or a modulo filter:
# Approach 1: Range with step 2 (Fastest & Most Pythonic!)
def find_even_nums(n):
return list(range(2, n + 1, 2))
# Approach 2: List Comprehension with Modulo Filter
def find_even_nums_comp(n):
return [x for x in range(1, n + 1) if x % 2 == 0]
# Testing our function
print(find_even_nums(8)) # Output: [2, 4, 6, 8]
print(find_even_nums(4)) # Output: [2, 4]
print(find_even_nums(2)) # Output: [2]
print(find_even_nums(1)) # Output: []
start = 2: First even number.stop = n + 1: Ensures inclusive upper bound n is included in the range.step = 2: Jumps by 2, automatically generating even numbers without modulo tests!range(1, n) stops at n - 1! Always use n + 1 when you want the range boundary to be inclusive of n.Use range(start, stop, step) for efficient numerical sequences. Next, let's build progressive spelling list patterns!
A function with no `return` hands back `None`, so a forgotten one surfaces as a `TypeError` at the call site rather than at the line that actually caused it.
`minutes * 60` returns an `int` when given an `int`, while `/` always produces a float regardless of the operands. Multiplication preserves the type; division does not.
`base * height / 2` always yields a float in Python 3 because `/` never returns an int, even for whole numbers. `//` floors instead, which is almost never what an area wants.