Lists & loops
Iterate, transform, and combine sequences with readable loop patterns.
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.
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:
…
How to Calculate the Average of a List of Numbers in Python
Compute the arithmetic mean of a numeric list using Python's built-in sum() and len() functions, returning 0.0 for an empty list.
def calculate_average(numbers):
if not numbers:
return 0.0
return sum(numbers) / len(numbers)
if __name__ == "__main__":
sample_numbers = [10, 20, 30, 40, 50]
result = calculate_average(sample_numbers)
print(f"Average: {result}")
How to Compute a Moving Average in Python
This code computes the moving average over a numeric list using an efficient sliding window sum, avoiding recomputation of each window.
def moving_average(data, window_size):
"""
Compute the moving average over a numeric list.
Args:
data: List of numeric values
window_size: Size of the sliding window (positive integer)
Returns:
List of moving averages, each representing the mean of a window
"""
…
How to Filter Even Numbers and Square Them in Python
Create two beginner-friendly helper functions that filter even numbers and compute squares of a number list using loops, then print the results along with the sum and average.
def get_even_numbers(numbers):
evens = []
for num in numbers:
if num % 2 == 0:
evens.append(num)
return evens
def get_squares(numbers):
squares = []
for num in numbers:
squares.append(num ** 2)
return squares
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers …
How to Summarize a List of Numbers in Python
Loop over a list of numbers to compute total, count, average, min, and max, then return them in a dictionary.
def summarize_numbers(numbers):
"""Return a dict with basic stats for a list of numbers."""
total = 0
count = 0
smallest = numbers[0]
largest = numbers[0]
for num in numbers:
total += num
count += 1
if num < smallest:
smallest = num
if num > largest:…
How to summarize and transform lists in Python
Compute count, sum, min, max, and average for a list and multiply each element by a factor using simple loops and built-in functions.
def summarize(data):
"""Return a summary of a list: count, sum, min, max, average."""
count = len(data)
total = sum(data)
minimum = min(data)
maximum = max(data)
average = total / count if count else 0
return count, total, minimum, maximum, average
def multiply_elements(data, factor=2):
…
Browse by section
Each section groups closely related Python snippets.
Lists & loops — Python code examples
What you will find here
This page collects lists & loops snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.