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.
Python code
26 linesfrom 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
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
- Use list comprehension with `random.randint` for a shorter one-liner: `data = [randint(1, max_val) for _ in range(size)]`.
- 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
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.