Reference library

Python Code Samples

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

6 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
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
OOP & classes easy

How to Compare Dataclass Instances by Specific Fields in Python

Use @dataclass(order=True) with field(compare=False) to control which fields determine ordering and equality between instances.

dataclasses comparison sorting
Python
from dataclasses import dataclass, field
from typing import Any

@dataclass(order=True)
class Person:
    name: str = field(compare=False)
    age: int
    height_cm: float
    priority: int = field(compare=False, default=0)

    def __repr__(self):
        return f"Person(name={self.name!r}, age={self.age}, height={s…
14 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
Testing & modern typing easy

How to Write a pytest Test Function with assert Equal in Python

Define simple pytest test functions that use assert to verify result equality and run them with pytest.main.

pytest unit testing assert
Python
import pytest

def add(a, b):
    return a + b

def test_add_positive_numbers():
    result = add(2, 3)
    assert result == 5

def test_add_negative_numbers():
    result = add(-2, -3)
    assert result == -5

def test_add_mixed_numbers():
    result = add(2, -3)
    assert result == -1

if __name__ == "__main__":
  …
11 0 Open
Database scaling & optimization easy

Hash index equality mock concept in Python

A simple hash index class in Python that stores key-value pairs in buckets and demonstrates basic equality-based lookup.

hash-index hash-table database
Python
class HashIndex:
    def __init__(self):
        self._buckets = {}

    def insert(self, key, value):
        """Insert a key-value pair into the hash index."""
        index = hash(key) % 10
        if index not in self._buckets:
            self._buckets[index] = []
        self._buckets[index].append((key, value))…
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.