Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Mock ELB Target Health Status in Python
Simulate AWS Elastic Load Balancer target health checks with a Python dict that mutates status and healthy host counts.
from random import randint
def elb_target_mock_status(target_id, healthy=True):
targets = {
1: {"Id": "i-001", "Status": "healthy", "Port": 80, "HealthyHostCount": 1},
2: {"Id": "i-002", "Status": "unhealthy", "Port": 80, "HealthyHostCount": 0},
3: {"Id": "i-003", "Status": "healthy", "Por…
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.…
Round Robin Load Balancer in Python
This code simulates round robin load balancing by distributing a list of requests evenly across a list of servers.
def round_robin_servers(requests: list[str], servers: list[str]) -> dict[str, list[str]]:
assignments = {server: [] for server in servers}
for idx, request in enumerate(requests):
server = servers[idx % len(servers)]
assignments[server].append(request)
return assignments
if __name__ == "_…
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 implement round-robin load balancing in Python
Implement a client-side round-robin load balancer that distributes requests sequentially across a list of mock servers using itertools.cycle.
import itertools
import random
class MockServer:
def __init__(self, name):
self.name = name
def handle_request(self, request_id):
return f"Server {self.name} handled request #{request_id}"
class RoundRobinLoadBalancer:
def __init__(self, servers):
self.servers = servers
…
Rebalance Shard Ranges Across Nodes in Python
A mock rebalancing function that shuffles shard ranges and distributes them evenly across nodes using round-robin assignment.
import random
from dataclasses import dataclass
@dataclass
class Shard:
id: int
start: int
end: int
def rebalance_shards(shards: list[Shard], node_count: int) -> dict[int, list[Shard]]:
"""Mock rebalancing of shard ranges across nodes."""
all_ranges = [(s.start, s.end) for s in shards]
random…
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.