Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Sample Random Items Without Replacement in Python
Select k random unique items from a sequence using random.sample for uniform, non-repeating selection.
import random
def sample_without_replacement(population, k):
"""Return k random items from population without replacement."""
if k > len(population):
raise ValueError("k cannot exceed population size")
# Use random.sample for O(k) time, no mutation of the original
return random.sample(populati…
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.
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…
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.
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…
How to Build a Weighted Random Load Balancer in Python
A Python load balancer mock that distributes requests across servers based on configurable weights using a cumulative weighted random selection algorithm.
import random
from collections import Counter
SERVERS = {
"server-a": 50,
"server-b": 30,
"server-c": 20,
}
def weighted_random_server(servers: dict[str, int]) -> str:
"""Select a server based on its weight (higher weight = more likely)."""
total_weight = sum(servers.values())
rand = random.…
Mock NATS queue group load balancing in Python
Simulates a NATS queue group where each message is delivered to exactly one subscriber using random selection with a lightweight mock.
import random
import time
from collections import defaultdict
class MockQueueGroup:
"""Mock a NATS queue group: each message is delivered to exactly one subscriber."""
def __init__(self, subscribers):
self.subscribers = subscribers
def publish(self, message):
receiver = random.choice(se…
How to Mock a Server-Side Load Balancer in Python
A simple Python class that mimics a server-side load balancer with round-robin, random, and least-connections selection strategies.
import itertools
import random
class LoadBalancer:
def __init__(self, servers=None):
self.servers = servers if servers else ["server1", "server2", "server3"]
self.counter = itertools.count(1)
def round_robin(self):
return next(self.counter) % len(self.servers)
def random_selectio…
How to do feature selection with VarianceThreshold in Python
This code demonstrates how to use scikit-learn's VarianceThreshold to remove low-variance features from a NumPy array, keeping only those that vary enough to be useful for modeling.
import numpy as np
from sklearn.feature_selection import VarianceThreshold
def main():
# Mock dataset: 4 samples, 5 features
X = np.array([
[0.1, 0.2, 1.0, 1.0, 0.5],
[0.2, 0.2, 0.0, 1.0, 0.4],
[0.1, 0.2, 1.0, 1.0, 0.6],
[0.3, 0.2, 1.0, 0.0, 0.5]
])
# Select features w…
How to simulate a contextual bandit in Python
Simulate a contextual multi-armed bandit with random features and epsilon-greedy action selection in 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…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.