Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Group Data by Category in Python
Group a list of (category, value) tuples into a dictionary of lists using the setdefault method.
def group_by_category(data):
"""Group list of (category, value) tuples into dictionaries of lists."""
groups = {}
for category, value in data:
groups.setdefault(category, []).append(value)
return groups
if __name__ == "__main__":
items = [
("fruit", "apple"),
("veg", "carro…
How to Write Simple XML Documents with ElementTree in Python
Create well-structured XML documents in memory using Python's built-in ElementTree module, complete with nested elements, attributes, and text content.
import xml.etree.ElementTree as ET
def create_xml_document():
# Create root element
root = ET.Element("catalog")
# Create a book element with attributes and children
book1 = ET.SubElement(root, "book", id="bk101")
ET.SubElement(book1, "author").text = "Gambardella, Matthew"
ET.SubElement(…
Build a Case-Insensitive Dict with a Wrapper Class in Python
Create a custom dict subclass that treats keys as case-insensitive by normalizing them to lowercase, with a full set of common dict methods.
class CaseInsensitiveDict:
def __init__(self, data=None):
self._data = {}
if data:
self.update(data)
def __setitem__(self, key, value):
self._data[str(key).lower()] = value
def __getitem__(self, key):
return self._data[str(key).lower()]
def __delitem__(sel…
How to Build a Two-Way Dictionary in Python
Implement a BiDict class that supports both forward key-to-value and reverse value-to-key lookups with a simple add, delete, and update API.
class BiDict:
def __init__(self, data=None):
self.forward = {}
self.backward = {}
if data:
self.update(data)
def update(self, data):
for key, value in data.items():
self[key] = value
def __setitem__(self, key, value):
self.forward[key] = val…
How to Create a Dict from Two Parallel Lists in Python (zip)
Build a dictionary by pairing elements from two parallel lists using Python's built-in zip function and dict constructor.
keys = ["name", "age", "city"]
values = ["Alice", 30, "New York"]
result = dict(zip(keys, values))
print(result)
How to Group a List of Dictionaries by Key in Python
Group a list of dictionaries by a specified key field using dict.setdefault to build a dictionary of lists.
def group_by_key(records, key):
grouped = {}
for record in records:
grouped.setdefault(record[key], []).append(record)
return grouped
if __name__ == "__main__":
data = [
{"name": "Alice", "dept": "engineering"},
{"name": "Bob", "dept": "sales"},
{"name": "Carol", "dept"…
LRU Cache with OrderedDict in Python
Implement an LRU cache using collections.OrderedDict to track insertion order and evict the least-recently-used item when capacity is exceeded.
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.cache = OrderedDict()
def get(self, key):
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(sel…
Graph Class with Adjacency Dict in Python
Build an undirected graph class using a dictionary of adjacency lists with methods to add vertices, edges, remove edges, and query neighbors.
class Graph:
def __init__(self):
self.adjacency = {}
def add_vertex(self, vertex):
if vertex not in self.adjacency:
self.adjacency[vertex] = []
def add_edge(self, u, v):
self.add_vertex(u)
self.add_vertex(v)
self.adjacency[u].append(v)
self.adja…
How to Build a Linked List Node Class in Python
Create a Node class and a LinkedList class with insert, remove, and display methods to manage a singly linked list.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
current = self.…
How to Implement a Queue Class in Python Using deque
Build a FIFO queue class in Python backed by the collections.deque container with enqueue, dequeue, peek, and size methods.
from collections import deque
class Queue:
def __init__(self):
self._items = deque()
def enqueue(self, item):
self._items.append(item)
def dequeue(self):
if self.is_empty():
raise IndexError("dequeue from empty queue")
return self._items.popleft()
…
How to Implement a Stack Class in Python
A complete Stack class implemented with a Python list, featuring push, pop, peek, is_empty, size, and a readable string representation.
class Stack:
def __init__(self):
self._items = []
def push(self, item):
"""Add an item to the top of the stack."""
self._items.append(item)
def pop(self):
"""Remove and return the top item. Raises IndexError if empty."""
if self.is_empty():
raise IndexE…
Implement Insert Delete GetRandom O(1) in Python
Build a RandomizedSet class that supports insert, delete, and get_random in average O(1) time using a list and a dictionary mapping values to indices.
import random
class RandomizedSet:
def __init__(self):
self.values = []
self.index_map = {}
def insert(self, val):
if val in self.index_map:
return False
self.index_map[val] = len(self.values)
self.values.append(val)
return True
def delete(self…
Implement Queue Using Two Stacks in Python
Python class that implements a FIFO queue using two stacks, with enqueue, dequeue, peek, and emptiness checks.
class QueueUsingStacks:
def __init__(self):
self.stack_in = []
self.stack_out = []
def enqueue(self, value):
self.stack_in.append(value)
def dequeue(self):
if not self.stack_out:
while self.stack_in:
self.stack_out.append(self.stack_in.pop())
…
Implement a Stack Using List Push Pop in Python
A minimal Stack class built on a Python list, with push, pop, peek, is_empty, and size methods, including empty-stack guards.
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if self.is_empty():
raise IndexError("pop from empty stack")
return self.items.pop()
def peek(self):
if self.is_empty():
raise…
How to Use TypedDict for Data Validation in Python
Define a TypedDict schema and validate raw dictionary input with type hints for safer, more readable data handling.
from typing import Any, Dict, List, Optional, Union, TypedDict, Literal
class Product(TypedDict):
product_id: int
name: str
price: Union[int, float]
in_stock: bool
tags: Optional[List[str]]
def validate_product(data: Dict[str, Any]) -> Product:
product_id: int = int(data["product_id"])
na…
How to Build a Simple Data Helper in Python for API Design
Create a beginner-friendly DataHelper class that demonstrates basic CRUD operations (add, get, list, remove) using an in-memory dictionary, ideal for learning API design concepts.
class DataHelper:
"""Simple data helper for beginners learning API design concepts."""
def __init__(self):
self._data = {}
def add_record(self, key, value):
"""Add a record to the store."""
self._data[key] = value
return f"Added: {key} -> {value}"
def get_…
How to Build a Message Stream Queue in Python
A beginner-friendly MessageStream class built on deque that sends messages one at a time, tracks unread counts, and records sent items.
from collections import deque
import time
class MessageStream:
def __init__(self, messages):
self._queue = deque(messages)
self._sent = []
def send_next(self):
if not self._queue:
return None
message = self._queue.popleft()
self._sent.append(message)
…
Consistent Hashing Cache Shard in Python
A minimal consistent hashing ring with virtual nodes that distributes cache keys across shards and minimizes re-mapping when a node is removed.
import hashlib
import bisect
class ConsistentHashRing:
def __init__(self, nodes=None, replicas=3):
self.replicas = replicas
self.ring = {}
self.sorted_keys = []
if nodes:
for node in nodes:
self.add_node(node)
def _hash(self, key):
return i…
How to Implement an LFU Cache in Python
Implement a Least Frequently Used (LFU) cache with frequency tracking dictionaries to evict the least accessed items when capacity is reached.
class LFUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.data = {}
self.freq = {}
self.min_freq = 0
def get(self, key: int) -> int:
if key not in self.data:
return -1
self._increment_freq(key)
return self.data[key]
…
Sliding Window Streaming Mock in Python
A simple Python class that maintains a sliding window of recent streaming values and computes the running average.
import time
import random
class StreamingMock:
"""Produces a stream of numbers using a sliding window."""
def __init__(self, window_size=5):
self.window = []
self.window_size = window_size
def push(self, value):
"""Add a value, sliding the window forward."""
s…
Model registry version mock in Python
A simple in-memory model registry that stores model versions with metadata and supports version listing and latest retrieval.
class ModelRegistry:
def __init__(self):
self.models = {}
def register(self, name, version, model_type, metrics=None):
if name not in self.models:
self.models[name] = []
entry = {
"version": version,
"model_type": model_type,
"metrics": m…
B-Tree Insert and In-Order Traversal in Python
Simulates a B-tree (order 2) with insert and split logic, then prints keys in sorted order via in-order traversal.
class BTreeNode:
def __init__(self, leaf=False):
self.leaf = leaf
self.keys = []
self.children = []
def is_full(self, t):
return len(self.keys) == 2 * t - 1
class BTree:
def __init__(self, t=2):
self.t = t
self.root = BTreeNode(leaf=True)
def insert(s…
How to Simulate a Stable Sort Cursor in Python
Build a MongoDB-style cursor mock that stably sorts records by a key while preserving original order for ties, with next() and rewind() methods.
```python
import random
class CursorStableSortMock:
"""Simulates stable sorting with a cursor-like pointer for MongoDB-style queries."""
def __init__(self, data, sort_key, reverse=False):
self.data = list(data)
self.sort_key = sort_key
self.reverse = reverse
self._index = …
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.