Reference library

Lists & loops

Iterate, transform, and combine sequences with readable loop patterns.

15 matches
Lists & loops easy

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.

random loops lists
Python
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:
   …
12 0 Open
Lists & loops easy

How to Build a Running Maximum List in Python

Compute a list where each element is the maximum of all numbers seen so far from an input list.

running-max iteration lists
Python
def running_maximum(numbers):
    result = []
    current_max = float('-inf')
    for num in numbers:
        if num > current_max:
            current_max = num
        result.append(current_max)
    return result

if __name__ == "__main__":
    numbers = [3, 1, 4, 1, 5, 9, 2, 6]
    max_list = running_maximum(number…
15 0 Open
Lists & loops easy

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.

average mean sum
Python
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}")
13 0 Open
Lists & loops easy

How to Compute Percentile Value from Sorted List in Python

Compute any percentile value from a sorted list using linear interpolation between ranks.

percentile statistics interpolation
Python
def percentile(sorted_data, percentile_value):
    """Return the value below which `percentile_value`% of data falls."""
    if not sorted_data:
        raise ValueError("Cannot compute percentile of empty list")
    if not 0 <= percentile_value <= 100:
        raise ValueError("Percentile must be between 0 and 100")
…
15 0 Open
Lists & loops easy

How to Compute Sliding Window Sum of Size k in Python

Compute the sum of every contiguous subarray of a fixed size k using an efficient O(n) sliding window technique.

sliding-window list sum
Python
def sliding_window_sum(nums, k):
    """Return a list of sums for each contiguous subarray of size k."""
    if not nums or k <= 0 or k > len(nums):
        return []
    
    result = []
    window_sum = sum(nums[:k])
    result.append(window_sum)
    
    for i in range(k, len(nums)):
        window_sum += nums[i] -…
13 0 Open
Lists & loops easy

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.

moving-average sliding-window lists
Python
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
    """
   …
14 0 Open
Lists & loops easy

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.

loops filtering math
Python
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 …
15 0 Open
Lists & loops easy

How to Find the Median of a List in Python

Compute the median of an unsorted numeric list using the statistics module in Python.

median statistics lists
Python
import statistics

def median_of_list(numbers):
    return statistics.median(numbers)

if __name__ == "__main__":
    sample = [7, 3, 1, 4, 9, 2, 8]
    print(median_of_list(sample))
12 0 Open
Lists & loops easy

How to Flatten One Level of a Nested List in Python

Flattens exactly one level of a nested list by extending the output with each inner list and appending non-list items.

flatten nested list list comprehension
Python
def flatten_one_level(nested_list):
    """Flatten one level of a nested list."""
    flattened = []
    for item in nested_list:
        if isinstance(item, list):
            flattened.extend(item)
        else:
            flattened.append(item)
    return flattened

if __name__ == "__main__":
    # Example with mi…
15 0 Open
Lists & loops easy

How to Parse a Comma String into a List of Integers in Python

Converts a comma-separated string into a list of integers, handling spaces and empty inputs.

csv parsing list-comprehension
Python
def parse_csv_to_ints(text: str) -> list[int]:
    """Parse a comma-separated string into a list of integers."""
    if not text.strip():
        return []
    return [int(part.strip()) for part in text.split(",") if part.strip()]

if __name__ == "__main__":
    sample = "10, 20, 30, 40, 50"
    result = parse_csv_to_…
13 0 Open
Lists & loops easy

How to Standardize a List with Z-Score Normalization in Python

This code computes the z-score for each number in a list, standardizing the data to have zero mean and unit variance using the statistics module.

z-score standardization statistics
Python
import statistics

def z_score_normalize(values):
    """Standardize a list of numbers using z-score normalization."""
    if not values or len(values) < 2:
        raise ValueError("Need at least 2 values for meaningful z-score normalization")
    
    mean = statistics.mean(values)
    std_dev = statistics.stdev(val…
14 0 Open
Lists & loops easy

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.

lists loops statistics
Python
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:…
16 0 Open
Lists & loops easy

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.

lists loops statistics
Python
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):
 …
13 0 Open
Lists & loops easy

How to unzip a list of pairs into two lists in Python

Split a list of (a, b) tuples into two separate lists by iterating with a for loop and appending each element to its own output list.

lists tuples loops
Python
def unzip(pairs):
    """Split a list of (a, b) pairs into two separate lists."""
    if not pairs:
        return [], []
    
    firsts = []
    seconds = []
    for a, b in pairs:
        firsts.append(a)
        seconds.append(b)
    
    return firsts, seconds


if __name__ == "__main__":
    pairs = [(1, 'a'), (…
14 0 Open
Lists & loops easy

Pairwise Adjacent Differences in a Python List

Computes the absolute differences between each pair of adjacent elements in a list using a concise list comprehension.

list-comprehension differences absolute-value
Python
def adjacent_differences(nums):
    """Return list of absolute differences between adjacent elements."""
    return [abs(nums[i] - nums[i + 1]) for i in range(len(nums) - 1)]


if __name__ == "__main__":
    sample = [3, 7, 2, 9, 5]
    diffs = adjacent_differences(sample)
    print("Original list:", sample)
    print…
14 0 Open

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.