Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

98 matches
Dictionaries & sets easy

How to Use ChainMap for Layered Config Lookup in Python

This code demonstrates using collections.ChainMap to combine multiple dictionaries into a single layered lookup, where earlier maps override later ones.

chainmap configuration collections
Python
from collections import ChainMap

defaults = {"theme": "light", "lang": "en", "debug": False}
user = {"lang": "de", "auto_save": True}
runtime = {"debug": True}

config = ChainMap(runtime, user, defaults)

if __name__ == "__main__":
    print("theme:", config["theme"])
    print("lang:", config["lang"])
    print("deb…
14 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…
13 0 Open
Dictionaries & sets easy

How to Use Dictionaries and Sets in Python for Beginners

Demonstrates Python dictionary operations and set operations with examples, including access, modification, defaults, and set algebra.

dictionary set beginner
Python
def demonstrate_collections():
    # Dictionary basics
    student = {
        "name": "Alice",
        "age": 20,
        "courses": ["Math", "Physics"]
    }
    print("Dictionary:", student)

    # Access and modify
    student["age"] = 21
    student["grade"] = "A"
    print("Modified:", student)

    # Get with d…
11 0 Open
Dictionaries & sets easy

How to Use a Frozenset as a Dict Key in Python

Demonstrates using an immutable frozenset as a hashable dictionary key, including equality and lookup with differently-ordered elements.

frozenset dictionary hashable
Python
frozen = frozenset({"a", "b", "c"})
mapping = {frozen: "set as hashable key"}
other_frozen = frozenset(["c", "b", "a"])
print(f"Are keys equal? {frozen == other_frozen}")
print(f"Lookup with different order: {mapping[other_frozen]}")
print(f"Hash matches: {hash(frozen) == hash(other_frozen)}")
13 0 Open
Dictionaries & sets easy

Multiset with Counter update and elements in Python

Demonstrates using collections.Counter as a multiset: updating counts with update() and iterating elements() to get repeated items.

counter multiset collections
Python
from collections import Counter

multiset = Counter(['apple', 'banana', 'apple'])

multiset.update(['banana', 'cherry', 'apple'])

print("Elements after update:", sorted(multiset.elements()))
print("Counts:", dict(multiset))
print("Most common:", multiset.most_common(2))
13 0 Open
OOP & classes easy

Composition over Inheritance: How to Build a Wallet Account in Python

Demonstrates composition by wrapping a WalletAccount class in an AuditedWallet decorator-like class to add behavior without changing the original class.

composition design-patterns oop
Python
class WalletAccount:
    def __init__(self, owner, balance=0.0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self.balance += amount
        return self.balance

    def withdraw(self, …
13 0 Open
OOP & classes easy

How to Implement Rich Comparison Ordering in Python Classes

This code demonstrates how to implement rich comparison operators (like <, <=, >, >=, ==, !=) in a Python class by defining __lt__ and __eq__, enabling sorting and ordering of custom objects.

rich comparison sorting operators
Python
class Task:
    def __init__(self, priority, name):
        self.priority = priority
        self.name = name

    def __lt__(self, other):
        if not isinstance(other, Task):
            return NotImplemented
        return self.priority < other.priority

    def __eq__(self, other):
        if not isinstance(oth…
12 0 Open
OOP & classes easy

How to Implement a Singleton Class in Python

This code demonstrates a classic Singleton pattern in Python by overriding __new__ to ensure only one instance of the class is created, even when instantiated multiple times.

singleton class oop
Python
class Singleton:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        self.value = 0


if __name__ == "__main__":
    s1 = Singleton()
    s2 = Singleton()
    s1.value = 42
    print…
15 0 Open
OOP & classes easy

How to Implement the Decorator Pattern in Python to Add Behavior

This Python code demonstrates the decorator pattern by wrapping a function to add logging behavior without modifying the original function.

decorator pattern logging
Python
import functools

def logger(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with {args} {kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

@logger
def add(a, b):
   …
11 0 Open
OOP & classes easy

How to Use IntEnum Arithmetic for Priority Levels in Python

Demonstrates Python IntEnum arithmetic for priority levels, showing how enum members behave like integers in calculations and comparisons.

enum intenum priority
Python
from enum import IntEnum

class Priority(IntEnum):
    LOW = 1
    MEDIUM = 5
    HIGH = 10
    CRITICAL = 20

if __name__ == "__main__":
    current = Priority.MEDIUM
    boosted = current + 3
    lowered = current - 2
    doubled = current * 2

    print(f"Current: {current} ({current.value})")
    print(f"Boosted (…
13 0 Open
OOP & classes easy

Python object equality: id vs value comparison

Demonstrates the difference between default identity comparison and custom equality, with a value-based class implementing __eq__ and __hash__.

oop equality hash
Python
import copy


class IdOnly:
    def __init__(self, name):
        self.name = name


class ValueId:
    def __init__(self, name):
        self.name = name

    def __eq__(self, other):
        return isinstance(other, ValueId) and self.name == other.name

    def __hash__(self):
        return hash(self.name)

    def…
12 0 Open
Algorithms & data structures easy

How to Combine filter and map with a List Comprehension in Python

This Python code demonstrates how to combine filtering and mapping in a single list comprehension and shows the equivalent filter() and map() approach.

list-comprehension filter map
Python
def square(x):
    return x * x

def is_even(x):
    return x % 2 == 0

numbers = [1, 2, 3, 4, 5, 6, 7, 8]

result = [square(x) for x in numbers if is_even(x)]

print(f"Original numbers: {numbers}")
print(f"Squares of even numbers: {result}")

# Combined filter + map equivalent
filtered = filter(is_even, numbers)
mapp…
13 0 Open
Algorithms & data structures easy

Split a String into Multiple Lines by Width in Python

Demonstrates a word-wrap algorithm that splits a message into rows without exceeding a maximum width.

strings word-wrap algorithm
Python
def split_message(text, max_width):
    words = text.split()
    rows = []
    current_row = []

    for word in words:
        if len(" ".join(current_row + [word])) > max_width:
            rows.append(" ".join(current_row))
            current_row = [word]
        else:
            current_row.append(word)

    if …
14 0 Open
Algorithms & data structures easy

Stable sort preserving equal order demo in Python

Demonstrates Python's stable sort, showing that elements with equal sort keys retain their original relative order.

sorting stable sort timsort
Python
from operator import itemgetter

def stable_sort_demo():
    data = [(3, "first"), (1, "second"), (3, "third"), (1, "fourth"), (2, "fifth")]
    print("Original:", data)
    
    # Sort by first element (the tuple's first value), keeping relative order of equal items
    sorted_data = sorted(data, key=itemgetter(0))
 …
13 0 Open
Comprehensions & generators easy

Build a lazy generator to read file lines in Python

Create a generator function that yields file lines one at a time, avoiding loading the entire file into memory, and demonstrate its lazy processing.

generator file-io lazy
Python
def lazy_lines(filepath):
    """Yield lines from a file one at a time without loading the whole file into memory."""
    with open(filepath, 'r', encoding='utf-8') as file:
        for line in file:
            yield line.rstrip('\n')


if __name__ == "__main__":
    # Create a sample file to demonstrate
    sample_c…
14 0 Open
Comprehensions & generators easy

Generator Function to Yield an Infinite Counter in Python

This code demonstrates a generator function that yields an infinite sequence of integers starting from a given value, allowing lazy, memory-efficient iteration.

generators infinite sequences yield
Python
def infinite_counter(start=0):
    count = start
    while True:
        yield count
        count += 1

if __name__ == "__main__":
    counter = infinite_counter(5)
    for _ in range(5):
        print(next(counter))
14 0 Open
Comprehensions & generators easy

How to Close a Generator and Handle GeneratorExit in Python

This Python code demonstrates how to explicitly close a generator using the close() method and handle the GeneratorExit exception through a finally block to run cleanup logic.

generators generator-exit close
Python
def countdown(n):
    try:
        while n > 0:
            yield n
            n -= 1
    finally:
        print(f"Generator closed after countdown completed")


if __name__ == "__main__":
    gen = countdown(5)
    print(next(gen))
    print(next(gen))
    gen.close()
    print("Generator closed explicitly")
12 0 Open
Comprehensions & generators easy

How to Parse Data with Generators and Comprehensions in Python

This code demonstrates using a generator expression to filter active users and a dictionary comprehension to aggregate scores by name.

generator expressions dictionary comprehensions filtering
Python
def parse_data_helper(raw_records):
    """Extract active users' names and scores from raw records."""
    parsed = (
        (record["name"], record["score"])
        for record in raw_records
        if record["active"] and record["score"] >= 0
    )
    return list(parsed)


def aggregate_scores(parsed_data):
    "…
15 0 Open
Comprehensions & generators easy

How to Use Comprehensions and Generators in Python

Demonstrate list, set, and dictionary comprehensions plus generator expressions and generator functions in one beginner-friendly script.

comprehensions generators yield
Python
def demonstrate_comprehensions_generators():
    # List comprehension: transform and filter in one line
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    squares = [num ** 2 for num in numbers if num % 2 == 0]
    print(f"Square of even numbers (list comprehension): {squares}")

    # Set comprehension: unique values
…
15 0 Open
Comprehensions & generators easy

Sum of Squares with a Generator Expression in Python

This code computes the sum of squares of integers from 1 to n using a generator expression, demonstrating a memory-efficient and concise way to aggregate a sequence.

generator sum squares
Python
def sum_of_squares(n):
    return sum(x * x for x in range(1, n + 1))

if __name__ == "__main__":
    print(f"Sum of squares from 1 to 5: {sum_of_squares(5)}")
    print(f"Sum of squares from 1 to 10: {sum_of_squares(10)}")
14 0 Open
Comprehensions & generators easy

Write Data Helpers with Comprehensions and Generators in Python

Demonstrates list, dict, and set comprehensions plus generator expressions and generator functions for building concise data helpers.

comprehensions generators data-helpers
Python
# Basic comprehensions and generators demo

# List comprehension: squares of evens
squares = [x * x for x in range(10) if x % 2 == 0]
print("List comp:", squares)

# Dictionary comprehension: char -> count
text = "hello"
char_counts = {c: text.count(c) for c in set(text)}
print("Dict comp:", char_counts)

# Set compre…
10 0 Open
AI & LLM integration patterns easy

Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo

This demo shows how to structure a function that explains its own reasoning step-by-step, mimicking chain-of-thought prompting for AI systems.

ai llm reasoning
Python
def solve_math_step_by_step(expression: str) -> str:
    """Solves a simple expression, showing each reasoning step."""
    # Step 1: Parse the expression (assume "a + b" or "a - b")
    parts = expression.split()
    a = int(parts[0])
    op = parts[1]
    b = int(parts[2])
    
    steps = []
    steps.append(f"Step…
16 0 Open
AI & LLM integration patterns easy

Demonstrate Prompt Injection Bypass in Python

Simulate why naive system prompt filters fail against prompt injection with casing and spacing variations.

prompt-injection llm-security demo
Python
# Demonstrate why system prompts can be bypassed by simulated user input
# This demo shows a naive filter being ignored via prompt injection

def process_user_message(message, system_rules):
    """Simulate an AI that follows system rules but gets tricked."""
    # Claim to check system rules
    for rule in system_ru…
14 0 Open
AI & LLM integration patterns easy

How to Convert Data to JSON and Back in Python

Convert a Python dict into a JSON string with indentation, then parse it back into a dict, demonstrating a common round-trip conversion for beginners.

json serialization conversion
Python
import json
from datetime import datetime

def convert_data(data):
    """Convert a dict into a JSON string and back to dict."""
    json_str = json.dumps(data, indent=2)
    parsed = json.loads(json_str)
    return json_str, parsed

def main():
    sample_data = {
        "user": "alice",
        "message": "hello",
…
11 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.