How to Count, Double, and Find Max in a Python List
Three beginner-friendly Python functions that count even numbers, double each value, and find the maximum in a list using simple loops.
Python code
34 linesdef count_even_numbers(numbers):
"""Return the count of even numbers in a list."""
count = 0
for num in numbers:
if num % 2 == 0:
count += 1
return count
def double_values(numbers):
"""Return a new list with each value doubled."""
doubled = []
for num in numbers:
doubled.append(num * 2)
return doubled
def find_max(numbers):
"""Return the largest value in a list."""
if not numbers:
return None
max_value = numbers[0]
for num in numbers:
if num > max_value:
max_value = num
return max_value
if __name__ == "__main__":
sample = [3, 7, 2, 9, 4, 6, 1]
print(f"Original list: {sample}")
print(f"Even count: {count_even_numbers(sample)}")
print(f"Doubled values: {double_values(sample)}")
print(f"Max value: {find_max(sample)}")
Output
Original list: [3, 7, 2, 9, 4, 6, 1]
Even count: 3
Doubled values: [6, 14, 4, 18, 8, 12, 2]
Max value: 9
How it works
Each function uses a for loop to iterate over the list. count_even_numbers checks num % 2 == 0 to identify even numbers and increments a counter. double_values builds a new list by appending num * 2 for every element. find_max initializes the maximum to the first element and updates it whenever a larger value is found; it returns None for an empty list. These patterns are fundamental for processing collections in Python.
Common mistakes
- assuming the input list is never empty in `find_max` — always handle that case
- modifying the original list instead of creating a new one in `double_values`
- comparing to `max_value` with `>=` instead of `>` in `find_max`, which is fine but changes behavior for duplicates
Variations
- Use list comprehension: `[num * 2 for num in numbers]` for doubling.
- Use built-in functions: `sum(1 for n in numbers if n % 2 == 0)` and `max(numbers)`.
Real-world use cases
- Counting the number of failed requests in a list of HTTP status codes to trigger alerts.
- Scaling product prices by a factor in an e‑commerce inventory import pipeline.
- Determining the highest salary in a list of employee records for analytics reports.
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.