Reference library

Python Code Samples

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

117 matches
Strings & text easy

How to Compare Two Strings in Python

Compares two string values and returns a detailed report with equality, case-insensitive comparison, lengths, and uppercase versions.

string-comparison case-insensitive helper-function
Python
def compare_data(first_value, second_value):
    """Compare two string values and return a report."""
    if first_value == second_value:
        status = "MATCH"
    else:
        status = "DIFFER"
    return {
        "first_value": first_value,
        "second_value": second_value,
        "status": status,
       …
12 0 Open
Strings & text easy

How to Use Template Strings for Substitution in Python

This code shows how to use Python's Template class for safe string substitution, replacing placeholders like $name with actual values.

template string substitution
Python
from string import Template

def format_user_message(name, role, company):
    template = Template("Hello $name! We are glad to have you as our $role at $company.")
    return template.substitute(name=name, role=role, company=company)

if __name__ == "__main__":
    result = format_user_message("Alice", "Python Develo…
11 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

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 Filter a List in Python with a Loop

Filter a list of numbers by a threshold using a for loop and append results to a new list, then print the filtered values and count.

filter for-loop lists
Python
ages = [34, 12, 45, 8, 67, 21, 18, 55, 3]
threshold = 18

adults = []
for age in ages:
    if age >= threshold:
        adults.append(age)

print("All ages:", ages)
print("Adults (18+):", adults)
print("Count of adults:", len(adults))
10 0 Open
Lists & loops easy

How to Get the Union of Two Lists Without Duplicates in Python

Merge two lists and remove duplicate values using a set, then convert back to a list.

set union merge
Python
def union_without_duplicates(list1, list2):
    return list(set(list1 + list2))

if __name__ == "__main__":
    list_a = [1, 2, 3, 4]
    list_b = [3, 4, 5, 6]
    result = union_without_duplicates(list_a, list_b)
    print(f"Union of {list_a} and {list_b}: {result}")
13 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 Safely Convert a List of Strings to Integers in Python

Convert a list of strings to integers while skipping invalid entries and collecting the failed values for inspection.

list conversion int conversion error handling
Python
def safe_to_int(values):
    """Safely convert a list of strings to integers, skipping invalid entries."""
    result = []
    errors = []
    for value in values:
        try:
            result.append(int(value))
        except (ValueError, TypeError):
            errors.append(value)
    return result, errors


if …
13 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

Add Type Hints to Function Parameters and Return in Python

Add type hints to function parameters and return values in Python for clearer, more maintainable code using the typing module.

type-hints typing annotations
Python
from typing import List, Optional, Dict


def average(numbers: List[float]) -> float:
    return sum(numbers) / len(numbers)


def full_name(first: str, last: Optional[str] = "") -> str:
    return f"{first} {last}".strip()


def build_user(name: str, age: int, email: Optional[str] = None) -> Dict[str, object]:
    us…
15 0 Open
Functions & basics easy

How to Count Items with Default Parameters in Python

Define a Python function that prints each item with a running counter, using default parameters to allow custom start values and step increments.

functions default-parameters loops
Python
def count_items(items, start=0, step=1):
    """Count items in a list with configurable start value and step."""
    count = start
    for item in items:
        print(f"{count}: {item}")
        count += step

if __name__ == "__main__":
    fruits = ["apple", "banana", "cherry"]
    print("Default parameters (start=0…
11 0 Open
Functions & basics easy

How to Define a Function with Default Parameter Values in Python

This code demonstrates defining a Python function with default parameter values, showing how to call it with zero, one, or two arguments.

functions default-parameters arguments
Python
def greet(name: str = "World", punctuation: str = "!") -> str:
    """Return a greeting message using default parameter values."""
    message = f"Hello, {name}{punctuation}"
    return message


if __name__ == "__main__":
    # Call with no arguments – uses both defaults
    print(greet())

    # Call with one argume…
13 0 Open
Functions & basics easy

How to Document Python Functions with Google Style Docstrings

Document a Python function with a Google style docstring to describe arguments and return values clearly.

docstrings documentation functions
Python
def calculate_rectangle_area(length: float, width: float) -> float:
    """Calculate the area of a rectangle.

    Args:
        length (float): The length of the rectangle in meters.
        width (float): The width of the rectangle in meters.

    Returns:
        float: The area of the rectangle in square meters.
 …
13 0 Open
Functions & basics easy

How to Parse Function Parameters with Defaults in Python

Create Python functions with default parameter values to make arguments optional and provide sensible fallbacks.

functions default-parameters arguments
Python
def greet(name, greeting="Hello", punctuation="!"):
    """Greet a person with customizable greeting and punctuation."""
    return f"{greeting}, {name}{punctuation}"

def describe_fruit(fruit, color="unknown", ripe=False):
    """Describe a fruit with optional attributes."""
    status = "ripe" if ripe else "not ripe…
14 0 Open
Functions & basics easy

How to Read Environment Variables in Python with Default Values

Retrieve an environment variable safely using os.getenv() with a fallback default when the variable is missing.

environment-variables os configuration
Python
import os

database_url = os.getenv("DATABASE_URL", "postgresql://localhost:5432/mydb")
print(f"Database URL: {database_url}")
10 0 Open
Functions & basics easy

How to Return Multiple Values from a Python Function

This code demonstrates how a Python function can return multiple values as a tuple, and how to unpack that tuple into individual variables.

functions tuple return-values
Python
def get_user_stats(name, score, level):
    """Return multiple values as a tuple."""
    return name, score, level

if __name__ == "__main__":
    result = get_user_stats("Alice", 95, 3)
    print(result)
    print(type(result))
    
    # Unpacking into individual variables
    player_name, player_score, player_level…
16 0 Open
Functions & basics easy

How to Use Default Parameter Values in Python Functions

Shows how to define and call Python functions with default parameter values, including overriding some or all defaults and using keyword arguments.

functions default-parameters arguments
Python
def greet(name, greeting="Hello", punctuation="!"):
    """Return a greeting message using default parameters."""
    return f"{greeting}, {name}{punctuation}"

if __name__ == "__main__":
    # Using defaults
    print(greet("Alice"))
    
    # Overriding first default
    print(greet("Bob", "Hi"))
    
    # Overrid…
14 0 Open
Functions & basics easy

How to Use Default Parameter Values in Python Functions

This code demonstrates how to define a Python function with default parameters and call it with varying numbers of arguments to see the defaults applied.

functions parameters defaults
Python
def greet(name, greeting="Hello", punctuation="!"):
    message = f"{greeting}, {name}{punctuation}"
    print(message)

if __name__ == "__main__":
    greet("Alice")
    greet("Bob", "Hi")
    greet("Charlie", "Hey", "?")
13 0 Open
Functions & basics easy

How to Validate Function Arguments in Python

Shows how to manually check argument types and values in a Python function, raising clear TypeError and ValueError messages.

validation function arguments type hints
Python
def calculate_area(length: float, width: float) -> float:
    """Calculate the area of a rectangle with manual type validation."""
    if not isinstance(length, (int, float)) or isinstance(length, bool):
        raise TypeError(f"length must be a number, got {type(length).__name__}")
    if not isinstance(width, (int,…
13 0 Open
Functions & basics easy

How to use function defaults in Python

Define Python functions with default parameter values so callers can omit arguments and use sensible fallbacks.

functions default-parameters basics
Python
def greet(name="Guest", greeting="Hello", punctuation="!"):
    """Return a greeting message using default parameters."""
    return f"{greeting}, {name}{punctuation}"

def describe_pet(pet_name, animal_type="dog"):
    """Display information about a pet with a default animal type."""
    print(f"I have a {animal_type…
15 0 Open
Functions & basics easy

Python Function Default Parameters Explained with Examples

Learn how to define Python functions with default parameter values and call them with fewer arguments than declared.

functions default-parameters args
Python
def greet(name, greeting="Hello", punctuation="!"):
    return f"{greeting}, {name}{punctuation}"

def calculate_area(length, width=1, unit="sq units"):
    area = length * width
    return f"Area: {area} {unit}"

if __name__ == "__main__":
    print(greet("Alice"))
    print(greet("Bob", "Hi"))
    print(greet("Charl…
14 0 Open
Errors & debugging easy

How to Catch KeyError with a Default Value in Python Dictionaries

Safely retrieve dictionary values while catching KeyError and handling None values by returning a default.

keyerror dictionary error-handling
Python
def get_value(data, key, default=None):
    """
    Safely get a value from a dictionary, returning a default if the key
    is missing or the value is None.
    """
    try:
        value = data[key]
        return value if value is not None else default
    except KeyError:
        return default


if __name__ == "_…
13 0 Open
Errors & debugging medium

How to Diff Two Dicts in Python for Config Drift

Recursively compare two dictionaries and report added, removed, and changed keys with their old and new values for debugging configuration drift.

dict diff config
Python
def diff_dicts(a, b, path=""):
    differences = []

    for key in a.keys() | b.keys():
        new_path = f"{path}.{key}" if path else key

        if key not in a:
            differences.append((new_path, "<missing>", b[key], "added"))
        elif key not in b:
            differences.append((new_path, a[key], "<…
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.