Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Build an OrderedDict insertion order demo in Python 3
Demonstrate how OrderedDict preserves insertion order, how updates keep position, and how re-insertion moves keys to the end.
from collections import OrderedDict
def demo_ordered_dict():
# Create an OrderedDict and insert items in a specific order
ordered = OrderedDict()
ordered['banana'] = 3
ordered['apple'] = 2
ordered['cherry'] = 5
ordered['date'] = 1
print("Insertion order preserved:")
for key, value in …
How to Sort Dictionary Keys Alphabetically in Python
This code returns a list of dictionary keys sorted alphabetically, using a case-insensitive comparison while preserving the original insertion order for keys that are equal.
data = {
"banana": 3,
"apple": 1,
"Cherry": 5,
"date": 2,
"apple": 4,
"Fig": 6,
"banana": 2,
}
def sort_dict_keys_alphabetically(d):
"""Return a list of keys sorted alphabetically (case-insensitive), stable for duplicates."""
return sorted(d.keys(), key=lambda k: k.lower())
if __n…
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…
Insert Multiple Values Into a Sorted List in Python
Insert multiple values into an already-sorted list while keeping it sorted using the bisect.insort function.
import bisect
def insert_sorted(sorted_list, values):
for value in values:
bisect.insort(sorted_list, value)
return sorted_list
if __name__ == "__main__":
original = [1, 3, 5, 7, 9]
new_values = [4, 6, 2, 8, 0]
result = insert_sorted(original, new_values)
print(f"Original: {original}"…
Insert an Element Every n Positions in Python
Insert a given element before or after every n-th position in a Python list, returning a new list with the placements applied.
def insert_every_n(seq, element, n, position="after"):
"""Insert an element before or after every n-th position in a list.
Args:
seq: Input list
element: Element to insert
n: Insert every n positions (n > 0)
position: 'before' or 'after' (default: 'after')
Returns:
…
How to compute diff stats (insertions, deletions) in Python
Parses a git diff text and counts the number of added and removed lines to produce insertion and deletion stats.
import re
from collections import Counter
def parse_diff(diff_text):
insertions = 0
deletions = 0
for line in diff_text.splitlines():
if line.startswith("+") and not line.startswith("+++"):
insertions += 1
elif line.startswith("-") and not line.startswith("---"):
d…
How to Use bisect.insort in Python to Maintain a Sorted List
Insert items into an already sorted list using Python's bisect.insort to keep it sorted efficiently in O(n) time.
import bisect
def maintain_sorted_list():
data = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_list = []
for num in data:
bisect.insort(sorted_list, num)
print("Original data:", data)
print("Sorted list maintained with insort:", sorted_list)
# Insert new values to maintain sorted orde…
How to Implement a Priority Queue for Messages in Python
Build a message priority queue with heapq and dataclasses that pops messages by priority, using sequence numbers to keep insertion order.
import heapq
from dataclasses import dataclass, field
from typing import Any
@dataclass(order=True)
class Message:
priority: int
sequence: int = field(compare=False)
content: str = field(compare=False)
class PriorityQueue:
def __init__(self):
self._heap = []
def push(self, priority: int,…
Exactly Once Processing Dedupe Mock in Python
Implements a streaming deduplicator using a set and queue to guarantee each item is processed exactly once while preserving insertion order.
from collections import deque
class DedupeStream:
def __init__(self):
self.seen = set()
self.queue = deque()
def add(self, item):
if item not in self.seen:
self.seen.add(item)
self.queue.append(item)
print(f"Processed: {item} (exactly once)")
…
How to Batch Load JSON Data in Python for Database Optimization
This code parses JSON data into records and loads them in batches to simulate efficient database insertion, reducing load and improving performance.
import json
import time
def parse_and_load(data, batch_size=100):
"""
Parse JSON data and batch-load into a list of dicts.
Demonstrates batching for database efficiency.
"""
records = json.loads(data)
batches = []
for i in range(0, len(records), batch_size):
batch = records[i:i + …
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.