Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

45 matches
Strings & text easy

How to Build a Text Processor in Python

This code defines functions to count words, sentences, and find the longest word in a text, then prints basic statistics like uppercase and lowercase versions.

text-processing strings word-count
Python
def count_words(text):
    return len(text.split())


def count_sentences(text):
    sentence_endings = ".!?"
    count = 0
    for char in text:
        if char in sentence_endings:
            count += 1
    return count


def longest_word(text):
    words = text.split()
    if not words:
        return ""
    retur…
14 0 Open
Strings & text easy

How to Inspect String Statistics in Python

A beginner-friendly function that returns detailed statistics about a string, including length, word count, character types, and easy text transformations.

strings text-analysis statistics
Python
def inspect_text(text: str) -> dict:
    """Return useful stats about a string for beginners."""
    words = text.split()
    return {
        "length": len(text),
        "word_count": len(words),
        "uppercase": sum(1 for ch in text if ch.isupper()),
        "lowercase": sum(1 for ch in text if ch.islower()),
 …
14 0 Open
Strings & text easy

How to Summarize Text Statistics in Python

This function returns basic statistics about a string, including character, word, and sentence counts, plus case and digit counts.

strings text-processing statistics
Python
def summarize_text(text):
    """Return basic statistics about a string."""
    words = text.split()
    return {
        "characters": len(text),
        "words": len(words),
        "sentences": text.count(".") + text.count("!") + text.count("?"),
        "uppercase": sum(c.isupper() for c in text),
        "lowerca…
13 0 Open
Strings & text easy

String helpers in Python: stats, reverse, and remove vowels

Three beginner-friendly Python functions compute text statistics, reverse word order, and strip vowels from a string.

string-manipulation text-stats vowel-removal
Python
def text_stats(text: str) -> dict:
    """Return basic statistics for a given text string."""
    words = text.split()
    return {
        "characters": len(text),
        "words": len(words),
        "sentences": text.count(".") + text.count("!") + text.count("?"),
        "uppercase": sum(1 for c in text if c.isupp…
13 0 Open
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:
   …
11 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 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))
11 0 Open
Lists & loops easy

How to Find the Mode in a Python List

Find the most frequent value (mode) in a Python list using the collections.Counter class, handling empty lists and ties.

mode counter frequency
Python
from collections import Counter

def find_mode(numbers):
    if not numbers:
        return None
    counts = Counter(numbers)
    max_count = max(counts.values())
    modes = [num for num, count in counts.items() if count == max_count]
    return modes[0] if len(modes) == 1 else modes

if __name__ == "__main__":
    …
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…
13 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:…
15 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):
 …
12 0 Open
Files & data easy

Detect Outliers in CSV Data Using Z-Score in Python

Read a CSV file and detect outliers in a numeric column by computing z-scores, flagging those exceeding a given threshold — no machine learning required.

outlier-detection z-score csv
Python
import csv
import statistics
from math import sqrt

def detect_outliers(csv_path, column_name, threshold=2.0):
    """Detect outliers in a numeric column using z-score method."""
    values = []
    with open(csv_path, 'r', newline='') as f:
        reader = csv.DictReader(f)
        if column_name not in reader.field…
49 0 Open
Files & data easy

How to Handle Missing Values in a CSV Numeric Column in Python

Clean missing entries in a CSV numeric column by filling them with the mean, median, a custom value, or dropping rows.

csv data-cleaning statistics
Python
import csv
from pathlib import Path
import statistics

def clean_csv_numeric(input_path: str, output_path: str, column: str, strategy: str = "mean") -> None:
    """
    Handles missing values in a numeric column of a CSV file.
    Strategies: 'mean', 'median', 'drop', or 'fill' with a specified value.
    """
    row…
12 0 Open
Dictionaries & sets easy

How to Use Counter for Most Common Elements in Python

This code demonstrates how to find the most frequent elements in a list using Python's Counter class from the collections module.

collections counter frequency
Python
from collections import Counter

def most_common_elements(items, n=1):
    """Return the n most common elements and their counts."""
    counter = Counter(items)
    return counter.most_common(n)

if __name__ == "__main__":
    data = ["apple", "banana", "apple", "orange", "banana", "apple", "grape"]
    print(most_co…
12 0 Open
Algorithms & data structures easy

Bucket Numbers into Histogram Bin Counts in Python

Partition a list of numbers into equal-width histogram bins and count how many fall into each bin using only the Python standard library.

histogram bins statistics
Python
from collections import Counter

def histogram_bins(numbers, num_bins):
    """Bucket numbers into histogram bin counts."""
    if not numbers:
        return []
    
    min_val = min(numbers)
    max_val = max(numbers)
    bin_width = (max_val - min_val) / num_bins
    
    # Handle edge case where all values are id…
17 0 Open
Comprehensions & generators easy

Normalize Data in Python with Comprehensions and Generators

Clean a list by dropping None values with a comprehension, then min-max normalize it using a lazy generator expression — a beginner-friendly data preparation pattern.

comprehensions generators normalization
Python
import statistics

# Sample raw data including missing and outlier-ish values
raw = [22, 18, None, 25, 30, 19, 22, 17, None, 28, 24]

# Clean the data: drop None values using a list comprehension
clean = [x for x in raw if x is not None]

# Normalize using min-max scaling with a generator expression
min_val = min(clea…
12 0 Open
AI & LLM integration patterns medium

Track GitHub Repository Growth in Python

A Python dashboard that fetches and displays GitHub repository statistics including stars, forks, creation date, and recent star activity using the GitHub API.

github api requests
Python
import requests
import json
from datetime import datetime, timedelta

def track_repo_growth(owner, repo):
    url = f"https://api.github.com/repos/{owner}/{repo}"
    headers = {"Accept": "application/vnd.github.v3+json"}
    response = requests.get(url, headers=headers)
    data = response.json()
    
    name = data…
42 0 Open
Automation & scripting medium

How to Generate Project Statistics Including Lines of Code and Complexity in Python

Walk through a Python script that scans a project directory for Python files, counts lines of code excluding blanks and comments, and estimates cyclomatic complexity by counting decision keywords.

code metrics lines of code cyclomatic complexity
Python
import os
from pathlib import Path

def count_lines_of_code(filepath):
    """Counts lines of code in a Python file, excluding blank lines and comments."""
    try:
        with open(filepath, 'r') as f:
            lines = f.readlines()
        code_lines = [line for line in lines if line.strip() and not line.strip()…
38 0 Open
Data pipelines & processing easy

How to Implement a Sliding Window Average in Python

Compute the average of the most recent N values in a stream using a bounded deque, efficiently updating the total as new values arrive.

deque sliding-window streaming
Python
from collections import deque


class SlidingWindowAverage:
    def __init__(self, window_size):
        self.window_size = window_size
        self.window = deque(maxlen=window_size)
        self.total = 0

    def add(self, value):
        if len(self.window) == self.window_size:
            self.total -= self.windo…
14 0 Open
Data pipelines & processing easy

How to detect anomalies in a column using z-score in Python

Detect outliers in a list of numbers using z-score statistics, flagging values that deviate significantly from the mean.

anomaly-detection z-score statistics
Python
import random

def z_score_anomaly_detection(data, threshold=2.0):
    """
    Detect anomalies in a list of numbers using z-score.
    """
    mean = sum(data) / len(data)
    variance = sum((x - mean) ** 2 for x in data) / len(data)
    std_dev = variance ** 0.5
    
    if std_dev == 0:
        return []
    
    a…
13 0 Open
Observability & SRE easy

How to Calculate Apdex Score from Latency Data in Python

Generate simulated latency samples and compute the Apdex score to gauge user satisfaction with an application's performance.

apdex latency observability
Python
import random
import statistics

def generate_latencies(count=100, base=100, stddev=30):
    return [max(0, random.gauss(base, stddev)) for _ in range(count)]

def apdex(latencies, threshold=200):
    satisfied = sum(1 for lat in latencies if lat < threshold)
    tolerating = sum(1 for lat in latencies if lat >= thres…
14 0 Open
Observability & SRE easy

How to Calculate Percentile Latency in Python

Generate mock latency samples with occasional spikes and compute 50th, 90th, 95th, and 99th percentile values in milliseconds.

percentile latency slo
Python
import random
import statistics

def generate_latency_samples(n=1000):
    """Generate realistic mock latency data (ms) with occasional spikes."""
    samples = []
    for _ in range(n):
        # Normal case: ~50ms with jitter
        base = random.gauss(50, 5)
        # 2% spike chance: slow downstream or GC pause
 …
12 0 Open
Observability & SRE medium

Summary Quantile Mock Sketch in Python

Build a memory-efficient sketch that stores sorted bins of data points to answer approximate quantile queries like median without keeping all values in memory.

quantile sketch statistics
Python
import random
import statistics
from collections import Counter

class SummaryQuantileSketch:
    """
    A simple sketch that stores a fixed-size summary of data (min, max, deciles)
    using sorted bins, then answers approximate quantile queries.
    """
    def __init__(self, bins=10):
        self.bins = bins
    …
12 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

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.