Reference library

Python Code Samples

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

7 matches
Files & data medium

How to Merge Sorted Chunk Files in Python

Merge multiple sorted text files into one sorted output file using a heap for efficient k-way merging.

heapq merge-sort external-sort
Python
import heapq


def merge_sorted_chunks(chunks, output_path):
    """Merge multiple sorted iterables into single sorted output file."""
    with open(output_path, "w") as out_f:
        # Open all chunk files
        handles = [open(chunk, "r") for chunk in chunks]
        try:
            # Heap of (value, index) tupl…
14 0 Open
Algorithms & data structures medium

How to Find the n Smallest Items in a Large List with heapq in Python

This code demonstrates how to efficiently extract the n smallest items from a large list using Python's heapq module and a manual max-heap approach.

heapq heaps large data
Python
import heapq

def n_smallest_iterable(data, n):
    """Return the n smallest items without loading the whole list."""
    if n <= 0:
        return []
    return heapq.nsmallest(n, data)

def n_smallest_manual(data, n):
    """Return the n smallest using a heap, O(n log k) time."""
    if n <= 0:
        return []
   …
13 0 Open
Algorithms & data structures medium

Merge k sorted lists in Python using a heap

Merge k individually sorted lists into one sorted list in Python using a min-heap.

heapq merge sorted-list
Python
import heapq

def merge_k_sorted_lists(lists):
    heap = []
    # Push the first element of each list onto the heap
    for i, lst in enumerate(lists):
        if lst:
            heapq.heappush(heap, (lst[0], i, 0))
    
    result = []
    while heap:
        val, list_idx, elem_idx = heapq.heappop(heap)
        re…
15 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 medium

Deduplicate events by ID within a window in Python

Deduplicate event streams by ID within sliding time windows, keeping the newest occurrence per window using heaps and sets.

deduplication events heapq
Python
import heapq
from collections import defaultdict

def deduplicate_events(events, window_size):
    """Return events deduplicated by id, keeping newest within each sliding window."""
    # Index events by (timestamp, id) for deterministic ordering
    events_by_id = defaultdict(list)
    for ts, eid, *payload in events…
14 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

Merge K Sorted Lists in Python with heapq

Merge k sorted lists into one sorted list in O(N log k) time using a min-heap of current elements.

heapq merge sorted-lists
Python
import heapq

def merge_k_sorted_lists(lists):
    heap = []
    for i, lst in enumerate(lists):
        if lst:  # only push non-empty lists
            heapq.heappush(heap, (lst[0], i, 0))
    result = []
    while heap:
        val, list_idx, elem_idx = heapq.heappop(heap)
        result.append(val)
        if elem…
13 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.