Reference library

Python Code Samples

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

496 matches
Strings & text easy

Extract Data from Strings in Python: Beginner's Guide

A beginner-friendly helper that splits a comma-separated string into a list, shows word count, and extracts the first and last words using Python's split() and join() methods.

string split join
Python
text = "python,string,extract,beginner"

words = text.split(",")

print("Full text:", text)
print("Word count:", len(words))
print("First word:", words[0])
print("Last word:", words[-1])

joined = " | ".join(words)
print("Joined with separator:", joined)
15 0 Open
Strings & text easy

Find Data From a String in Python: Stats, Clean, Keywords

Three helper functions for beginners: compute character/word/sentence stats, normalize whitespace and case, and extract unique sorted keywords from a string.

strings text-processing keywords
Python
def get_text_stats(text):
    """Return basic statistics about a string."""
    words = text.split()
    sentences = text.replace('!', '.').replace('?', '.').split('.')
    sentences = [s for s in sentences if s.strip()]
    return {
        'characters': len(text),
        'words': len(words),
        'sentences': le…
14 0 Open
Strings & text easy

How to Convert Data to Strings in Python

Convert common data types like bytes, numbers, containers, and None to readable strings with a safe helper function.

strings conversion type-conversion
Python
def to_str(value):
    """Convert common types to a readable string, safe for beginners."""
    if isinstance(value, bytes):
        return value.decode("utf-8")
    if isinstance(value, (dict, list, tuple, set)):
        return str(value)
    if value is None:
        return ""
    return str(value)


if __name__ == …
11 0 Open
Strings & text easy

How to Detect Expired Domains Using Python

Parse a list of domain registration data and compare expiry dates to today to find expired domains.

datetime date-parsing domain-check
Python
import datetime

# List of test domains with fake registration and expiry dates
# Format: (domain, registration_date, expiry_date)
test_domains = [
    ('example.com', '2020-01-15', '2024-01-15'),  # Expired
    ('google.com', '1997-09-15', '2026-09-15'),   # Still active
    ('test-site.org', '2019-06-01', '2023-06-0…
51 0 Open
Strings & text easy

How to Detect PII in Documents Using Python

Use regex patterns to automatically detect emails, phone numbers, SSNs, and credit card numbers in text documents.

pii regex data-privacy
Python
import re
from typing import List, Dict

def detect_pii(text: str) -> Dict[str, List[str]]:
    patterns = {
        "email": r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}",
        "phone": r"\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}",
        "ssn": r"\b\d{3}-\d{2}-\d{4}\b",
        "credit_card": r"\b\d{4}[- ]?\d{4}[-…
51 0 Open
Strings & text easy

How to Extract Digits Only from a String in Python

This code uses a regular expression to remove all non-digit characters from a mixed string, returning only the digits.

regex string manipulation data cleaning
Python
import re

def extract_digits(text):
    """Return only the digits from the given text as a string."""
    return re.sub(r'\D', '', text)

if __name__ == "__main__":
    mixed = "abc123def456!@#789"
    result = extract_digits(mixed)
    print(result)
12 0 Open
Strings & text easy

How to Filter Text to Only Letters, Numbers, and Spaces in Python

A beginner-friendly function that filters a string to keep only alphabetic characters, digits, and spaces, removing punctuation and symbols.

text-filtering strings beginner
Python
def filter_text(text, keep_alpha=True, keep_digits=True, keep_spaces=True):
    allowed = set()
    if keep_alpha:
        allowed.update("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
    if keep_digits:
        allowed.update("0123456789")
    if keep_spaces:
        allowed.add(" ")
    return "".join(ch f…
11 0 Open
Strings & text easy

How to Group Data by Category in Python

Group a list of (category, value) tuples into a dictionary of lists using the setdefault method.

grouping dictionaries setdefault
Python
def group_by_category(data):
    """Group list of (category, value) tuples into dictionaries of lists."""
    groups = {}
    for category, value in data:
        groups.setdefault(category, []).append(value)
    return groups

if __name__ == "__main__":
    items = [
        ("fruit", "apple"),
        ("veg", "carro…
12 0 Open
Strings & text easy

How to Slugify a String in Python

Convert any text into a URL-friendly slug using the standard library's unicodedata and re modules.

slugify string url
Python
import re
import unicodedata

def slugify(text):
    text = unicodedata.normalize('NFKD', text)
    text = text.encode('ascii', 'ignore').decode('ascii')
    text = re.sub(r'[^\w\s-]', '', text).strip().lower()
    text = re.sub(r'[-\s]+', '-', text)
    return text

if __name__ == "__main__":
    title = "Hello, Worl…
14 0 Open
Strings & text easy

Normalize unicode accents to ASCII in Python

This code converts accented Unicode characters to ASCII equivalents using the standard library's unicodedata module.

unicode accents normalization
Python
import unicodedata

def normalize_accents(text: str) -> str:
    """Convert accented unicode characters to ASCII equivalents."""
    decomposed = unicodedata.normalize('NFD', text)
    ascii_text = ''.join(
        char for char in decomposed
        if unicodedata.category(char) != 'Mn'
    )
    return unicodedata.n…
14 0 Open
Lists & loops easy

Compare Two Lists in Python: Common, Only in First, Only in Second

A beginner-friendly helper that loops over two lists and returns items common to both, items only in the first list, and items only in the second list.

lists comparison loops
Python
def compare_lists(list1, list2):
    common = []
    only_in_first = []
    only_in_second = []
    
    for item in list1:
        if item in list2:
            common.append(item)
        else:
            only_in_first.append(item)
    
    for item in list2:
        if item not in list1:
            only_in_second…
14 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

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 Convert Data Types in Python Lists

Convert a mixed list of values to integers, floats, or strings based on their content, with graceful fallback for unparseable strings.

type-conversion loops lists
Python
def convert_data(data):
    """Convert a mixed list of values to strings, ints, and floats."""
    result = []
    for item in data:
        if isinstance(item, (int, float)):
            result.append(str(item))
        elif isinstance(item, str):
            try:
                if '.' in item:
                    r…
13 0 Open
Lists & loops easy

How to Filter None Values from a Mixed List in Python

Filter None values from a mixed Python list using a list comprehension with the `is not None` condition.

filter list-comprehension none
Python
mixed_list = [1, None, "hello", None, 3.14, None, [1, 2], None]

filtered_list = [item for item in mixed_list if item is not None]

print(f"Original list: {mixed_list}")
print(f"Filtered list: {filtered_list}")
print(f"Original length: {len(mixed_list)}, Filtered length: {len(filtered_list)}")
15 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
Lists & loops easy

How to Normalize a List of Numbers to the 0-1 Range in Python

Scale a list of numbers so the minimum becomes 0 and the maximum becomes 1 using min-max normalization.

normalization lists data-science
Python
def min_max_normalize(values):
    """Normalize a list of numbers to the [0, 1] range."""
    if not values:
        return []
    min_val = min(values)
    max_val = max(values)
    if min_val == max_val:
        return [0.0] * len(values)
    return [(x - min_val) / (max_val - min_val) for x in values]


if __name__…
12 0 Open
Lists & loops easy

How to Parse Delimited Data into a Python List

Splits a pipe-delimited string, strips whitespace, filters empty items, and returns a clean list with a loop.

strings lists loops
Python
def parse_data(raw_data):
    """Parse a pipe-delimited string into a list of cleaned items."""
    items = raw_data.split("|")
    parsed = []
    for item in items:
        cleaned = item.strip()
        if cleaned:
            parsed.append(cleaned)
    return parsed


if __name__ == "__main__":
    data = "  apple…
15 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 Validate List Data in Python

A beginner-friendly validation helper that checks if data is a list, enforces minimum length, and optionally verifies item types with clear error messages.

validation lists loops
Python
def validate_data(data, expected_types=None, min_length=1):
    """Validate that data is a non-empty list and optionally check item types."""
    if not isinstance(data, list):
        return False, f"Expected a list, got {type(data).__name__}"
    
    if len(data) < min_length:
        return False, f"List must have…
16 0 Open
Lists & loops easy

How to check list items by type and emptiness in Python

Loop through a list with enumerate(), classify each item as empty, number, or text, and print a formatted status for each element.

lists loops enumerate
Python
def check_data(data):
    """Check each item in a list and print whether it's valid."""
    for i, item in enumerate(data):
        if item is None or item == "":
            status = "empty"
        elif isinstance(item, (int, float)):
            status = "number"
        else:
            status = "text"
        pr…
14 0 Open
Lists & loops easy

Replace Negative Values in a List with Python

This code defines a function that replaces every negative number in a list with a replacement value, defaulting to zero, using a list comprehension.

list-comprehension data-cleaning list-transformation
Python
def replace_if_negative(values, replacement=0):
    return [replacement if value < 0 else value for value in values]

if __name__ == "__main__":
    numbers = [5, -3, 8, -1, 0, -7, 2]
    result = replace_if_negative(numbers)
    print(f"Original: {numbers}")
    print(f"Replaced: {result}")
14 0 Open
Functions & basics easy

Build a Progress Callback Function for Loops in Python

Create a reusable progress callback that receives per-step data and lets callers log or update a UI as a loop runs.

callback loops progress
Python
def run_with_progress(items, desc="Processing", step_callback=None):
    """Run a loop with progress updates via callback."""
    total = len(items)
    for idx, item in enumerate(items):
        # Process the item (simulated work here)
        result = item * 2

        # Build progress data dictionary
        if ste…
14 0 Open
Functions & basics medium

How to Parse Function Signatures in Python with inspect

Extract a function's parameter names, kinds, defaults, annotations, and return type using Python's built-in inspect module.

inspect function signature introspection
Python
import inspect

def example_function(a: int, b: str = "default", *args, c: float = 1.5, **kwargs) -> bool:
    """An example function with various parameter types."""
    return True

def parse_signature(func):
    """Parse a function's signature using the inspect module."""
    sig = inspect.signature(func)
    param…
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.