Reference library

Python Code Samples

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

19 matches
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
Dictionaries & sets easy

How to Find the Intersection of Permission Sets in Python

This code defines a function that takes a list of permission sets and returns a set containing only the permissions common to all sets, with a short-circuit for empty results.

sets intersection permissions
Python
from typing import Set

def intersect_permissions(permission_sets: list[Set[str]]) -> Set[str]:
    """
    Given a list of permission sets, return the common permissions
    present in every set.
    """
    if not permission_sets:
        return set()
    
    common = permission_sets[0]
    for perm_set in permissi…
11 0 Open
Modern tooling easy

How to Build a Chainable Filter Helper in Python

A beginner-friendly dataclass helper that chains filters, uniqueness, and slicing on any sequence, returning a plain list at the end.

dataclass chaining filter
Python
from dataclasses import dataclass
from typing import Callable, Iterator, Sequence, TypeVar

T = TypeVar("T")


@dataclass
class FilterAssistant:
    """Beginner-friendly helper to filter any collection."""

    data: Sequence[T]

    def where(self, predicate: Callable[[T], bool]) -> "FilterAssistant":
        return …
14 0 Open
Modern tooling medium

How to set up mypy strict mode in Python

Demonstrates how to configure and run mypy in strict mode to enforce full type annotation coverage across a Python project.

mypy type-hints strict-mode
Python
from typing import Dict, Optional


def describe_user(name: str, age: int, email: Optional[str] = None) -> Dict[str, object]:
    """Build a user description dictionary with strict type annotations."""
    user: Dict[str, object] = {"name": name, "age": age}
    if email is not None:
        user["email"] = email
    …
13 0 Open
Testing & modern typing easy

Format Data with Type Hints in Python

Build a validated person dict with modern type hints and optional list handling.

type-hints typing data-formatting
Python
from typing import Any, Dict, List, Optional, Union

JsonValue = Union[str, int, float, bool, None, List["JsonValue"], Dict[str, "JsonValue"]]

def format_person(name: str, age: int, hobbies: Optional[List[str]] = None) -> Dict[str, Any]:
    """Build a person dict with validated typing."""
    if not name or age < 0:…
12 0 Open
Testing & modern typing easy

How to Convert Strings to Types in Python Using TypeVar

A beginner-friendly helper that converts a string to int, float, bool, or str with type hints and graceful failure handling.

typing type-hints conversion
Python
from typing import TypeVar, Optional

T = TypeVar("T")

def convert_data(value: str, target_type: type[T]) -> Optional[T]:
    """Convert string value to target type; return None on failure."""
    try:
        if target_type is int:
            return int(value)
        elif target_type is float:
            return f…
13 0 Open
Testing & modern typing easy

How to Filter Data in Python with Type Hints

A reusable filter_data helper uses optional predicates and numeric bounds with modern Python type hints.

filtering type-hints generics
Python
from typing import Iterable, TypeVar, Callable, Any

T = TypeVar("T")

def filter_data(
    items: Iterable[T],
    predicate: Callable[[T], bool] | None = None,
    *,
    min_value: float | None = None,
    max_value: float | None = None,
) -> list[T]:
    """Filter items by predicate and/or numeric bounds."""
    r…
11 0 Open
Testing & modern typing easy

How to Group Data by Key in Python with Type Hints

Group a list of dictionaries by a specified key using a typed helper function and print a summary of each group.

grouping type-hints dictionaries
Python
from typing import Any, Dict, List, TypeVar, Union

T = TypeVar("T")

def group_by(data: List[Dict[str, Any]], key: str) -> Dict[Any, List[Dict[str, Any]]]:
    """Group a list of dictionaries by a given key."""
    grouped: Dict[Any, List[Dict[str, Any]]] = {}
    for item in data:
        value = item.get(key)
     …
11 0 Open
Testing & modern typing easy

How to Parse Data with Type Hints in Python

A beginner-friendly helper that parses simple dictionary- or list-like strings into typed Python structures using modern typing annotations.

type-hints parsing typing
Python
from typing import Any, Dict, List, Union


def parse_data(raw: str) -> Union[Dict[str, Any], List[Any], str]:
    """Parse a simple string into structured data using type hints."""
    cleaned = raw.strip()
    
    if not cleaned:
        return {}
    
    if cleaned.startswith("{") and cleaned.endswith("}"):
     …
10 0 Open
Testing & modern typing easy

How to Use Basic Type Hints (int, str) for Return Values in Python

Declare a simple function with int and str type hints and a typed return value in Python.

type-hints annotations functions
Python
def greet(name: str, age: int) -> str:
    return f"{name} is {age} years old."


if __name__ == "__main__":
    print(greet("Alice", 30))
11 0 Open
Testing & modern typing easy

How to Use Literal Type Hints in Python

Use typing.Literal to restrict a function parameter to specific allowed string values and get static type checking.

typing type-hints literal
Python
from typing import Literal

def get_status_message(status: Literal["active", "inactive", "pending"]) -> str:
    """Return a message based on the status value."""
    if status == "active":
        return "Account is active"
    elif status == "inactive":
        return "Account is inactive"
    else:
        return "…
14 0 Open
Testing & modern typing easy

How to Use Python Type Hints for Beginners

Build a data helper module with basic type hints — Union, Optional, List, Dict, Any, and TypeVar — to make your code clearer and safer.

type-hints typing annotations
Python
from typing import Any, Union, Optional, List, Dict, Tuple, Callable, TypeVar

T = TypeVar("T")

def describe(value: Any) -> str:
    """Return a human-readable description of the value's type."""
    if isinstance(value, list):
        return f"list of {len(value)} items"
    elif isinstance(value, dict):
        ret…
12 0 Open
Testing & modern typing easy

How to Use TypedDict and Dataclasses in Python

Create typed data structures with TypedDict and dataclasses, then use them as helper functions for describing objects in a type-safe way.

typing typdict dataclass
Python
from typing import TypedDict, NotRequired, Optional
from dataclasses import dataclass


class User(TypedDict):
    name: str
    age: NotRequired[int]
    email: Optional[str]


@dataclass
class Product:
    id: int
    title: str
    price: float = 0.0


def describe_user(user: User) -> str:
    age = user.get("age",…
11 0 Open
Testing & modern typing medium

How to Use TypedDict for Data Validation in Python

Define a TypedDict schema and validate raw dictionary input with type hints for safer, more readable data handling.

typeddict typing validation
Python
from typing import Any, Dict, List, Optional, Union, TypedDict, Literal

class Product(TypedDict):
    product_id: int
    name: str
    price: Union[int, float]
    in_stock: bool
    tags: Optional[List[str]]

def validate_product(data: Dict[str, Any]) -> Product:
    product_id: int = int(data["product_id"])
    na…
13 0 Open
Testing & modern typing easy

How to Use TypedDict for Structured Dict Typing in Python

Define and use TypedDict to add type hints to dictionaries, improving code clarity and enabling static type checking in your Python projects.

typing typeddict type-hints
Python
from typing import TypedDict


class User(TypedDict):
    name: str
    age: int
    email: str


def greet(user: User) -> str:
    return f"Hello {user['name']}, age {user['age']}, contact {user['email']}"


if __name__ == "__main__":
    alice: User = {"name": "Alice", "age": 30, "email": "alice@example.com"}
    pr…
11 0 Open
Testing & modern typing easy

How to Use Union Type Hints in Python

This code demonstrates how to use Union type hints to specify that a parameter can accept multiple types (int, float, str) and handle them accordingly.

type-hints union typing
Python
from typing import Union

def process_value(value: Union[int, float, str]) -> str:
    if isinstance(value, (int, float)):
        return f"Number: {value * 2}"
    return f"String: {value.upper()}"

if __name__ == "__main__":
    print(process_value(10))
    print(process_value(3.14))
    print(process_value("hello"))
13 0 Open
Testing & modern typing medium

How to Validate Data in Python with Typing Hints

Build a runtime validation helper that checks values against Python type hints like Optional, list, and basic types.

typing validation type-hints
Python
from typing import Any, Optional, Union, TypeVar, get_origin, get_args

T = TypeVar("T")

def validate(value: Any, expected_type: type) -> Optional[str]:
    """Returns an error message if value doesn't match expected_type, else None."""
    # Handle Optional[...] types
    origin = get_origin(expected_type)
    if or…
12 0 Open
Testing & modern typing easy

How to Validate Dataclass Fields with Python Type Hints

A beginner-friendly helper that checks if instance attributes match their declared type hints using dataclasses and get_type_hints.

dataclasses type-hints validation
Python
from typing import Any, TypeVar, get_type_hints
from dataclasses import dataclass

T = TypeVar("T")

@dataclass
class User:
    name: str
    age: int
    email: str

def validate_fields(obj: Any) -> dict[str, bool]:
    """Check if object attributes match declared type hints."""
    hints = get_type_hints(obj.__class…
12 0 Open
Testing & modern typing easy

How to use Optional type hint in Python

Use the Optional type hint to indicate a parameter can be a string or None, with an example function that handles both cases.

typing optional type-hints
Python
from typing import Optional

def greet(name: Optional[str]) -> str:
    if name is None:
        return "Hello, anonymous!"
    else:
        return f"Hello, {name}!"

if __name__ == "__main__":
    print(greet("Alice"))
    print(greet(None))
10 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.