How to Loop Through Lists in Python for Beginners
Transform, filter, sum, and find the maximum in a Python list using basic for loops and conditionals.
Python code
41 linesdef transform_data(numbers):
"""Basic transformation examples using lists and loops."""
doubled = []
for n in numbers:
doubled.append(n * 2)
return doubled
def filter_even(numbers):
"""Keep only even numbers using a loop and condition."""
evens = []
for n in numbers:
if n % 2 == 0:
evens.append(n)
return evens
def sum_all(numbers):
"""Add up all numbers using a loop."""
total = 0
for n in numbers:
total += n
return total
def find_max(numbers):
"""Track the largest value in a loop."""
largest = numbers[0]
for n in numbers:
if n > largest:
largest = n
return largest
if __name__ == "__main__":
sample = [3, 7, 2, 9, 4]
print("Original:", sample)
print("Doubled:", transform_data(sample))
print("Evens:", filter_even(sample))
print("Sum:", sum_all(sample))
print("Max:", find_max(sample))
Output
Original: [3, 7, 2, 9, 4]
Doubled: [6, 14, 4, 18, 8]
Evens: [2, 4]
Sum: 25
Max: 9
How it works
These four functions demonstrate the fundamental loop patterns every Python beginner needs. transform_data appends a new value to an empty list on each iteration, building a result list. filter_even uses a conditional inside the loop to keep only values that satisfy a predicate. sum_all accumulates a running total, and find_max tracks the largest element seen so far by comparing each value. Together they show how loops can read, transform, and summarize list data.
Common mistakes
- Forgetting to initialize the result list or accumulator before the loop
- Using `return` inside the loop instead of after it, which exits early
- Assuming `find_max` works on an empty list — `numbers[0]` raises IndexError
- Modifying a list while iterating over it, which can skip elements
Variations
- Use list comprehensions, e.g. `[n * 2 for n in numbers]` for `transform_data`
- Use built-in functions like `sum(numbers)` and `max(numbers)` for simpler one-liners
Real-world use cases
- Normalizing raw sensor readings by scaling every value before plotting or storing.
- Filtering out invalid transactions from a daily batch before writing to a database.
- Computing total revenue and highest order value from a list of sales amounts.
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.