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.

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

Python code

41 lines
Python 3.9+
def 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

stdout
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

  1. Use list comprehensions, e.g. `[n * 2 for n in numbers]` for `transform_data`
  2. 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

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.