Reference library

Python Code Samples

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

78 matches
OOP & classes easy

How to Call a Parent Class __init__ with super() in Python

Shows how to chain __init__ calls through a class hierarchy using super(), so each class sets its own attributes while reusing the parent's initialization logic.

oop inheritance super
Python
class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species
        print(f"Animal init: {self.name}, {self.species}")

class Mammal(Animal):
    def __init__(self, name, species, fur_color):
        super().__init__(name, species)
        self.fur_color = fur_color
   …
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

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 medium

Understanding Multiple Inheritance Method Resolution Order in Python

This code demonstrates how Python's MRO determines which greet method is called in a diamond inheritance scenario, and prints the full MRO for class D.

multiple inheritance mro inheritance
Python
class A:
    def greet(self):
        return "Hello from A"

class B(A):
    def greet(self):
        return "Hello from B"

class C(A):
    def greet(self):
        return "Hello from C"

class D(B, C):
    pass


if __name__ == "__main__":
    d = D()
    print(d.greet())
    print(D.__mro__)
12 0 Open
Algorithms & data structures easy

Depth First Search Traversal Order in Python

Recursive depth-first search that returns the visit order of nodes in an adjacency list graph starting from a given node.

dfs graph traversal
Python
def dfs_order(adj, start):
    visited = set()
    order = []

    def dfs(node):
        visited.add(node)
        order.append(node)
        for neighbor in adj.get(node, []):
            if neighbor not in visited:
                dfs(neighbor)

    dfs(start)
    return order


if __name__ == "__main__":
    # Dem…
15 0 Open
Algorithms & data structures easy

Find Elements in One Python List but Not Another

Return a new list containing only the elements from list A that are not present in list B, preserving duplicates and order.

list difference set membership filtering
Python
def difference_elements(a, b):
    """Return elements present in list a but not in list b."""
    set_b = set(b)
    return [item for item in a if item not in set_b]

if __name__ == "__main__":
    a = [1, 2, 3, 4, 5, 3, 2]
    b = [2, 4, 6]
    result = difference_elements(a, b)
    print(f"A: {a}")
    print(f"B: {b…
14 0 Open
Algorithms & data structures easy

How to Compute the Cartesian Product of Two Lists in Python

Generates all ordered pairs from two lists using itertools.product and prints each combination.

itertools cartesian-product combinations
Python
from itertools import product

# Two small input lists
list_a = [1, 2, 3]
list_b = ["x", "y"]

# Compute the Cartesian product
result = list(product(list_a, list_b))

# Display the result
print("Cartesian product of", list_a, "and", list_b, "is:")
for pair in result:
    print(pair)
15 0 Open
Algorithms & data structures easy

How to Get the Breadth-First Traversal Order of a Graph in Python

Performs a breadth-first search on an adjacency list and returns the order nodes are visited, using a deque for efficient queue operations.

graph bfs queue
Python
from collections import deque

def bfs_order(adjacency, start=0):
    """Return the order nodes are visited in a breadth-first traversal."""
    visited = set()
    order = []
    queue = deque([start])
    visited.add(start)

    while queue:
        node = queue.popleft()
        order.append(node)

        for neig…
14 0 Open
Algorithms & data structures easy

How to Heapify a List into a Min Heap with heapq in Python

Convert any list into a valid min heap in-place using Python's heapq.heapify(), then pop the smallest element to verify heap order.

heapq min heap heapify
Python
import heapq

data = [5, 3, 8, 1, 9, 2, 7, 4, 6]
print("Original list:", data)

heapq.heapify(data)
print("Min heap:", data)

popped = heapq.heappop(data)
print("Smallest element popped:", popped)
print("Heap after pop:", data)
14 0 Open
Algorithms & data structures easy

How to Remove Banned Values from a List in Python

Filters a list by removing elements present in a banned set, preserving the original order.

list set filter
Python
def remove_banned(values, banned):
    banned_set = set(banned)
    return [item for item in values if item not in banned_set]


if __name__ == "__main__":
    values = [1, 2, 3, 4, 5, 2, 6, 3, 7]
    banned = [2, 3]
    result = remove_banned(values, banned)
    print(result)
12 0 Open
Algorithms & data structures easy

How to Remove Duplicates in Python Preserving Order

Removes duplicate items from a list while keeping the first occurrence order intact using a set for fast membership checks.

deduplication set list
Python
def remove_duplicates_preserving_order(items):
    seen = set()
    result = []
    for item in items:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

if __name__ == "__main__":
    sample = [3, 1, 2, 1, 3, 4, 2, 5]
    unique_items = remove_duplicates_preserv…
14 0 Open
Algorithms & data structures easy

Move Zeroes to End in Python Maintaining Order

In-place algorithm that moves all zeroes to the end of a list while preserving the relative order of non-zero elements.

two-pointers in-place array
Python
def move_zeroes(nums):
    non_zero_index = 0
    for i in range(len(nums)):
        if nums[i] != 0:
            nums[non_zero_index], nums[i] = nums[i], nums[non_zero_index]
            non_zero_index += 1
    return nums

if __name__ == "__main__":
    example = [0, 1, 0, 3, 12]
    result = move_zeroes(example)
  …
14 0 Open
Algorithms & data structures easy

Reorder a List by Odd Even Indices in Python

Splits a list into two sublists based on 1-based index parity, then concatenates odd-indexed elements before even-indexed ones.

list indices reorder
Python
def reorder_by_odd_even(items):
    """Reorders a list so that elements at odd indices come first,
    followed by elements at even indices (1-based).
    
    Example: [0,1,2,3,4,5,6] -> [1,3,5,0,2,4,6]
    """
    odds = [items[i] for i in range(1, len(items), 2)]
    evens = [items[i] for i in range(0, len(items), …
18 0 Open
Algorithms & data structures easy

Segregate Negative Numbers Before Positives in Python

Reorders a list so all negative numbers appear before non-negative numbers while preserving the original relative order of elements.

lists partition stability
Python
def segregate_negatives(numbers):
    """Segregate negatives before positives without altering relative order."""
    negatives = [n for n in numbers if n < 0]
    positives = [n for n in numbers if n >= 0]
    return negatives + positives


if __name__ == "__main__":
    sample = [3, -1, 4, -5, 2, -9, 0]
    result =…
14 0 Open
Algorithms & data structures easy

Sort list by multiple keys with tuple ordering in Python

Sort a list of dictionaries by multiple criteria — surname, age, then score descending — using a tuple key and negation.

sorting tuples lambda
Python
def sort_multi_key(data):
    # Sorts by surname, then age, then score descending
    return sorted(
        data,
        key=lambda person: (
            person['surname'].lower(),
            person['age'],
            -person['score']  # negative to reverse sort by score
        )
    )


if __name__ == "__main__"…
14 0 Open
Algorithms & data structures easy

Stable merge two lists by custom comparator in Python

Merge two lists into one sorted output using a custom comparator while maintaining the original order of equal elements.

merge stable-sort custom-comparator
Python
from functools import cmp_to_key

def compare(x, y):
    # Custom comparator: sorts by length first, then by original index for stability
    if len(x) != len(y):
        return len(x) - len(y)
    return 0  # Equal keys preserve original order (stable)

def merge_stable(left, right, cmp_func):
    result = []
    i =…
13 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

How to Generate Permutations of Length r in Python

Generate all ordered arrangements of length r from a given list of elements using itertools.permutations.

permutations itertools combinatorics
Python
from itertools import permutations

def generate_permutations(elements, r):
    """Generate all r-length permutations of the given elements."""
    return list(permutations(elements, r))

if __name__ == "__main__":
    elements = ['A', 'B', 'C']
    r = 2
    result = generate_permutations(elements, r)
    print(f"Ele…
14 0 Open
Comprehensions & generators easy

Merge Data with Comprehension and Generator in Python

Merge user and order data using a dictionary comprehension for lookups and a generator expression to filter and transform orders.

dictionary-comprehension generator-expression data-merging
Python
def merge_data(users, orders):
    """
    Merge user and order data using a dictionary comprehension
    and a generator expression for filtering.
    """
    # Build a lookup: user_id -> user name
    user_map = {user["id"]: user["name"] for user in users}

    # Generator: yield orders with user names attached
    …
14 0 Open
Comprehensions & generators medium

Merge Sorted Iterators with a Heap Generator in Python

Merge multiple sorted iterators into a single sorted stream using a heap and generator, yielding values lazily in order.

heapq generator merge
Python
import heapq

def merge_sorted_iterators(*iterators):
    heap = []
    for idx, iterator in enumerate(iterators):
        try:
            value = next(iterator)
            heapq.heappush(heap, (value, idx, iterator))
        except StopIteration:
            continue

    while heap:
        value, idx, iterator = …
15 0 Open
Data pipelines & processing easy

How to Sort a List of Dictionaries by Key in Python

A reusable helper function that sorts a list of dictionaries by a specified key, with optional descending order support.

sorting dictionaries data-pipelines
Python
from typing import List

def sort_records(records: List[dict], key: str, descending: bool = False) -> List[dict]:
    """Sort a list of dictionaries by a specified key."""
    return sorted(records, key=lambda record: record[key], reverse=descending)


def demonstrate_sorting() -> None:
    users = [
        {"name": …
12 0 Open
Data pipelines & processing medium

How to Topologically Sort a DAG in Python

Compute a valid execution order for tasks with dependencies using Kahn's algorithm in Python.

dag topological-sort graph
Python
from collections import defaultdict, deque


def topological_order(dependencies):
    graph = defaultdict(list)
    in_degree = defaultdict(int)
    tasks = set(dependencies.keys())

    for task, depends_on in dependencies.items():
        for d in depends_on:
            graph[d].append(task)
            in_degree[t…
11 0 Open
Data pipelines & processing medium

Implement an Out-of-Order Sort Buffer with a Heap in Python

Buffers out-of-order indices from a stream and emits them in sorted order using a min-heap with a sliding window.

heapq sorting streaming
Python
import heapq
from collections import deque


class OutOfOrderSorter:
    def __init__(self, buffer_size):
        self.buffer_size = buffer_size
        self.buffer = deque(maxlen=buffer_size)
        self.heap = []
        self.next_expected_index = 0
        self.result = []

    def push(self, item):
        heapq.…
12 0 Open
Concurrency & performance medium

How to Run Coroutines Concurrently with asyncio.gather in Python

Run multiple async coroutines concurrently and collect their results in the order they were passed.

asyncio concurrency gather
Python
import asyncio


async def fetch_data(name: str, delay: float) -> str:
    """Simulate an async operation (e.g., API call) with a delay."""
    await asyncio.sleep(delay)
    return f"{name} data (after {delay}s)"


async def main() -> None:
    """Run multiple coroutines concurrently with asyncio.gather."""
    resul…
15 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.