Generate Data Helper for Beginners in Python

Define two functions that create a random list of integers and then compute basic summary statistics like count, total, average, maximum, and minimum using simple loops.

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

Python code

26 lines
Python 3.9+
from random import randint

def build_dataset(size: int, max_val: int) -> list[int]:
    data = []
    for _ in range(size):
        data.append(randint(1, max_val))
    return data

def summarize(data: list[int]) -> dict[str, float]:
    total = 0
    maximum = data[0]
    minimum = data[0]
    for value in data:
        total += value
        if value > maximum:
            maximum = value
        if value < minimum:
            minimum = value
    average = total / len(data)
    return {"count": len(data), "total": total, "average": average, "max": maximum, "min": minimum}

if __name__ == "__main__":
    values = build_dataset(10, 20)
    print("Generated data:", values)
    stats = summarize(values)
    print("Summary:", stats)

Output

stdout
Generated data: [3, 19, 7, 12, 2, 20, 15, 9, 5, 11]
Summary: {'count': 10, 'total': 103, 'average': 10.3, 'max': 20, 'min': 2}

How it works

The build_dataset function uses a loop to append size random integers between 1 and max_val (inclusive) to an initially empty list. summarize then iterates over the list once, accumulating the total and updating the maximum and minimum values inside that single pass. The average is computed by dividing the total by the number of elements. Since the data always has at least one element in this flow, indexing data[0] for the initial max and min is safe. Returning results as a dictionary keeps the summary compact and easy to read.

Common mistakes

  • Forgetting to handle an empty list, which would raise an IndexError when accessing data[0].
  • Using `max` and `min` as variable names and shadowing the built-in functions.
  • Initializing average as an integer and losing the decimal part instead of using float division.

Variations

  1. Use list comprehension with `random.randint` for a shorter one-liner: `data = [randint(1, max_val) for _ in range(size)]`.
  2. Use built-in functions to compute stats: `total = sum(data)`, `average = total / len(data)`, `max(data)`, `min(data)`.

Real-world use cases

  • Creating synthetic datasets to test algorithms or visualization scripts during development.
  • Generating random sample data for demos, tutorials, or mock dashboards.
  • Simulating sensor readings or random events for a quick prototype or data pipeline smoke test.

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.