Reference library

Python Code Samples

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

36 matches
Strings & text easy

How to Check Palindrome in Python (Ignore Case and Spaces)

Check whether a string is a palindrome while ignoring case, spaces, and all non-alphanumeric characters using Python's filter and string reversal.

palindrome string case-insensitive
Python
def is_palindrome(text: str) -> bool:
    cleaned = ''.join(char.lower() for char in text if char.isalnum())
    return cleaned == cleaned[::-1]

if __name__ == "__main__":
    test_cases = [
        "A man, a plan, a canal: Panama",
        "race a car",
        "Was it a car or a cat I saw?",
        "hello",
      …
14 0 Open
Strings & text easy

How to Check if a String is Alphanumeric in Python

Uses the built-in str.isalnum() method to test whether a string contains only letters and numbers.

string alphanumeric validation
Python
def is_alphanumeric(s: str) -> bool:
    return s.isalnum()

if __name__ == "__main__":
    test_cases = ["Hello123", "Hello World", "12345", "", "Hello@World", "Python3"]
    for case in test_cases:
        result = is_alphanumeric(case)
        print(f"{case!r:15} -> {result}")
13 0 Open
Strings & text easy

How to Check if a String is Numeric in Python

This code provides a function to determine if a string represents a valid numeric value using Python's built-in float() conversion.

numeric validation strings
Python
def is_numeric(s):
    """Check if a string represents a valid numeric value."""
    try:
        float(s)
        return True
    except (ValueError, TypeError):
        return False

if __name__ == "__main__":
    test_cases = ["123", "-45.67", "3.14e10", "0x1A", "abc", "12.5.6", "  42  ", ""]
    for case in test_c…
13 0 Open
Lists & loops easy

Extract Data by Type from a List in Python: Numbers and Strings

Loop through a mixed list to filter out numeric and string values into separate lists.

lists filtering type-checking
Python
def extract_numbers(items):
    """Extract all numeric values from a mixed list."""
    numbers = []
    for item in items:
        if isinstance(item, (int, float)) and not isinstance(item, bool):
            numbers.append(item)
    return numbers


def extract_strings(items):
    """Extract all string values from a…
14 0 Open
Lists & loops easy

Find Local Minima (Valleys) in a Numeric List in Python

This code finds indices of all local minima (valleys) in a numeric list, including edge cases, using a simple loop that compares each element with its neighbors.

local minima valleys list
Python
def find_local_minima(numbers):
    """Find indices of local minima (valleys) in a numeric list.
    
    A value is a local minimum if it's less than or equal to its neighbors.
    Edge elements are considered minima if they're less than or equal to their single neighbor.
    """
    if not numbers:
        return []…
14 0 Open
Lists & loops easy

Find Maximum Value in a List of Numbers in Python

Iterate through a list with a for loop to manually find and return the maximum numeric value.

max list loop
Python
def find_max(numbers):
    """Return the maximum value in a list of numbers."""
    if not numbers:
        return None
    max_value = numbers[0]
    for num in numbers[1:]:
        if num > max_value:
            max_value = num
    return max_value

if __name__ == "__main__":
    sample_list = [3, 7, 2, 15, 9, 11]
…
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 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 Find Local Maxima in a Python List

Return the indices of all local maxima in a numeric list, where a peak is an element greater than both its immediate neighbors.

local-maxima peaks list
Python
def find_peaks(numbers):
    """
    Return the indices of local maxima in a numeric list.
    A local maximum is an element greater than both its neighbors.
    """
    if len(numbers) < 3:
        return []
    
    peaks = []
    for i in range(1, len(numbers) - 1):
        if numbers[i] > numbers[i - 1] and number…
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 Normalize a List of Numbers in Python

This Python function normalizes a list of numeric values to the range [0, 1] using min-max scaling, returning a new list and leaving the original unchanged.

lists loops normalization
Python
def normalize(data):
    """
    Normalize a list of numeric values to the range [0, 1].
    Returns a new list, leaving the original unchanged.
    """
    if not data:
        return []
    
    min_val = min(data)
    max_val = max(data)
    
    # Handle the edge case where all values are identical
    if min_val …
17 0 Open
Errors & debugging easy

How to Catch ValueError in Python (try except)

Handle invalid numeric input by catching ValueError in a try/except block and returning a friendly error message.

errors exception handling valueerror
Python
def parse_number(text):
    try:
        number = int(text)
        return f"Parsed number: {number}"
    except ValueError as error:
        return f"Error: '{text}' is not a valid number ({error})"


if __name__ == "__main__":
    examples = ["42", "hello", "3.14", "100"]
    for item in examples:
        print(pars…
11 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
OOP & classes easy

How to Convert Data Types in Python with a Helper Class

This code defines a beginner-friendly OOP helper class for common data conversions like string to list, list to dict, JSON string, and CSV row, with an advanced subclass for numeric casting.

oop classes data-conversion
Python
class DataConverter:
    """A beginner-friendly helper class for common data conversions."""
    
    def __init__(self, data):
        self.data = data
    
    def to_list(self):
        """Convert string data (comma-separated) to a list."""
        if isinstance(self.data, str):
            return [item.strip() for…
14 0 Open
Algorithms & data structures easy

How to Compute Cosine Similarity Between Two Vectors in Python

This code calculates the cosine similarity between two numeric vectors using the dot product and Euclidean norms, returning a value between -1 and 1.

cosine similarity vectors math
Python
import math

def cosine_similarity(vec_a, vec_b):
    if len(vec_a) != len(vec_b):
        raise ValueError("Vectors must have the same length")
    
    dot_product = sum(a * b for a, b in zip(vec_a, vec_b))
    norm_a = math.sqrt(sum(a * a for a in vec_a))
    norm_b = math.sqrt(sum(b * b for b in vec_b))
    
    i…
14 0 Open
Algorithms & data structures easy

How to Compute the Dot Product of Two Lists in Python

Compute the dot product of two equal-length numeric lists using a generator expression with zip and sum.

dot product zip sum
Python
def dot_product(list1, list2):
    """
    Compute the dot product of two numeric lists.
    The lists must have the same length.
    """
    if len(list1) != len(list2):
        raise ValueError("Lists must have the same length")
    
    return sum(a * b for a, b in zip(list1, list2))


if __name__ == "__main__":
  …
13 0 Open
Comprehensions & generators easy

How to Use Comprehensions and Generators to Check Data in Python

A beginner-friendly helper that filters numeric values, computes squares and cubes with comprehensions and a generator, and returns a summary dictionary.

comprehensions generators data-checking
Python
def check_data(iterable):
    """Return a summary of numeric data using comprehensions and a generator."""
    values = [item for item in iterable if isinstance(item, (int, float))]
    squares = [x ** 2 for x in values if x > 0]
    cubes = (x ** 3 for x in values if x > 0)
    cube_list = list(cubes)
    return {
  …
13 0 Open
Comprehensions & generators easy

How to Use List Comprehensions and Generators in Python

Analyze a list of numbers using a list comprehension to square evens, a generator for sum, and a generator expression for the maximum squared value.

comprehensions generators list-comprehension
Python
def analyze_numbers(numbers):
    squared = [n ** 2 for n in numbers if n % 2 == 0]
    total = sum(n for n in numbers)
    max_squared = max((n ** 2 for n in numbers), default=0)
    return squared, total, max_squared


if __name__ == "__main__":
    data = [1, 2, 3, 4, 5, 6]
    evens_squared, total_sum, max_sq = an…
11 0 Open
Automation & scripting medium

Automatically Generate Charts from CSV Files with One Command

Read a CSV file with headers, extract the first two numeric columns, and save a matplotlib line chart as a PNG image.

csv matplotlib charting
Python
import csv
import sys
from pathlib import Path
import matplotlib.pyplot as plt

def generate_chart(csv_path: str) -> None:
    """Read a CSV file with headers and plot the first two numeric columns."""
    data = []
    with open(csv_path, 'r', newline='') as f:
        reader = csv.reader(f)
        headers = next(re…
64 0 Open
Automation & scripting easy

Rename Files in Folder with Numeric Prefix in Python

Renames all files in a folder by adding a sequential numeric prefix (e.g., 01_, 02_) to each filename using pathlib.

file-renaming pathlib automation
Python
from pathlib import Path

def rename_with_numeric_prefix(folder_path):
    folder = Path(folder_path)
    for index, file_path in enumerate(folder.iterdir(), start=1):
        if file_path.is_file():
            new_name = f"{index:02d}_{file_path.name}"
            new_path = file_path.with_name(new_name)
           …
13 0 Open
Data pipelines & processing easy

ETL in Python: Extract CSV, Transform Dict, Load JSON

Build a simple ETL pipeline in Python that reads a CSV file, transforms each row (stripping whitespace and converting numeric fields), and writes the result to JSON.

etl csv json
Python
import csv
import json
from pathlib import Path

def extract_csv(file_path):
    """Read CSV file and return list of row dictionaries."""
    with Path(file_path).open('r', newline='', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        return list(reader)

def transform_dicts(rows):
    """Transform ro…
13 0 Open
Data pipelines & processing easy

How to Filter Data in Python

Filter a list of dictionaries by exact key-value matches or numerical ranges using concise list comprehensions.

filtering list-comprehension dictionaries
Python
from typing import List, Dict, Any


def filter_data(
    data: List[Dict[str, Any]], key: str, value: Any
) -> List[Dict[str, Any]]:
    """Return records where data[key] equals value."""
    return [record for record in data if record.get(key) == value]


def filter_by_range(
    data: List[Dict[str, Any]], key: str…
12 0 Open
Data pipelines & processing easy

How to Process CSV Data in Python with a Data Helper

Build a beginner-friendly data helper in Python that loads a CSV file, filters rows by a condition, and summarizes numeric fields.

csv data-processing pathlib
Python
import csv
from pathlib import Path

DATA = [
    {"name": "Alice", "score": 88, "passed": True},
    {"name": "Bob", "score": 42, "passed": False},
    {"name": "Carol", "score": 95, "passed": True},
]


def load_csv(file_path: Path) -> list[dict]:
    with file_path.open(newline="", encoding="utf-8") as f:
        r…
13 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.