Reference library

Python Code Samples

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

3 matches
Algorithms & data structures medium

Quickselect in Python: Find the kth Smallest Element

Python implementation of the Quickselect algorithm to find the kth smallest element in an unsorted list with average O(n) time complexity.

quickselect selection algorithm
Python
def quickselect(arr, k):
    """
    Returns the k-th smallest element (0-indexed) using Quickselect.
    Average: O(n), Worst: O(n^2)
    """
    if len(arr) == 1:
        return arr[0]

    pivot = arr[-1]
    left = [x for x in arr[:-1] if x <= pivot]
    right = [x for x in arr[:-1] if x > pivot]

    if k < len(l…
16 0 Open
Concurrency & performance medium

How to Mock anyio.run Backends (asyncio vs trio) in Python

Demonstrates how to mock anyio.run to verify backend selection (asyncio or trio) without actually running the event loop.

anyio async testing
Python
import anyio
from unittest.mock import Mock, patch


async def fetch_data():
    await anyio.sleep(0.1)
    return {"data": 42}


def run_with_backend(backend: str):
    async def main():
        result = await fetch_data()
        print(f"[{backend}] Result: {result}")

    anyio.run(main, backend=backend)


if __nam…
14 0 Open
A/B testing & experimentation medium

How to simulate a contextual bandit in Python

Simulate a contextual multi-armed bandit with random features and epsilon-greedy action selection in Python.

bandit-algorithms simulation epsilon-greedy
Python
import random


class ContextualBandit:
    def __init__(self, n_actions=3, n_features=4):
        self.n_actions = n_actions
        self.n_features = n_features
        self.theta = [random.random() for _ in range(n_actions * n_features)]

    def mock_context(self):
        return [random.uniform(-1, 1) for _ in ra…
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.