Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
Find Most Active Contributors in a Repository with Python
Filter recent commits by date and count the most active contributors using Counter and datetime.
from collections import Counter
from datetime import datetime, timedelta
# Simulated commit data
commits = [
{"author": "Alice", "timestamp": datetime.now() - timedelta(days=1)},
{"author": "Bob", "timestamp": datetime.now() - timedelta(days=2)},
{"author": "Alice", "timestamp": datetime.now() - timedelta…
How to Build a Frequency Map from a List in Python
This code builds a dictionary that maps each unique element in a list to its count using the Counter class from the collections module.
from collections import Counter
def build_frequency_map(values):
"""Return a dictionary mapping each unique value to its frequency."""
return dict(Counter(values))
if __name__ == "__main__":
data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
freq_map = build_frequency_map(data)
prin…
How to Find the Mode in a Python List
Find the most frequent value (mode) in a Python list using the collections.Counter class, handling empty lists and ties.
from collections import Counter
def find_mode(numbers):
if not numbers:
return None
counts = Counter(numbers)
max_count = max(counts.values())
modes = [num for num, count in counts.items() if count == max_count]
return modes[0] if len(modes) == 1 else modes
if __name__ == "__main__":
…
How to Record Last N Errors with a Ring Buffer in Python
Use collections.deque with maxlen to keep only the most recent N error messages while discarding older entries automatically.
import collections
class ErrorRecorder:
def __init__(self, size):
self.buffer = collections.deque(maxlen=size)
def record_error(self, message):
self.buffer.append(message)
def get_errors(self):
return list(self.buffer)
if __name__ == "__main__":
recorder = ErrorRecorder(3)
…
Build a defaultdict histogram of categories in Python
Count occurrences of each category in a list using collections.defaultdict(int) for automatic initialization.
from collections import defaultdict
def build_category_histogram(items):
"""Count occurrences of each category in a list of items."""
histogram = defaultdict(int)
for item in items:
histogram[item] += 1
return dict(histogram)
if __name__ == "__main__":
categories = ["fruit", "vegetable", …
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 …
Convert namedtuple to dict with asdict in Python
Convert a namedtuple instance into an ordinary dictionary using the asdict function from the collections module's namedtuple utility.
from collections import namedtuple, asdict
def main():
# Define a namedtuple for a person
Person = namedtuple("Person", ["name", "age", "city"])
person = Person(name="Alice", age=30, city="New York")
# Convert namedtuple to dict
person_dict = asdict(person)
print("Original namedtuple…
Count Word Frequency in Python with dict
Count how often each word appears in a text using Python's collections.Counter and regular expressions.
from collections import Counter
import re
def count_word_frequency(text):
"""Count frequency of each word in text (case-insensitive)."""
words = re.findall(r"\b\w+\b", text.lower())
return dict(Counter(words))
if __name__ == "__main__":
sample_text = "The quick brown fox jumps over the lazy dog. The …
How to Convert a Counter to a Plain Dict with Sorted Items in Python
This code converts a collections.Counter into a regular dictionary with items sorted by key, useful for stable, readable output.
from collections import Counter
def counter_to_sorted_dict(counter):
"""Convert a Counter to a plain dict with sorted items."""
return dict(sorted(counter.items()))
if __name__ == "__main__":
# Example usage
data = Counter(['apple', 'banana', 'apple', 'cherry', 'banana', 'date', 'apple'])
print("…
How to Count Tags with Sets and Dictionaries in Python
Count tag frequencies and collect unique tags from a list of dictionaries using Counter and sets in Python.
from collections import Counter
import json
def count_tags(entries):
"""Count tag frequencies across a list of entry dicts, using sets/dicts."""
tag_counter = Counter()
all_tags = set()
for entry in entries:
tags = set(entry["tags"])
all_tags.update(tags)
tag_counter.update(ta…
How to Count Word Frequencies in Python with Counter and Sets
This code processes a text string by lowercasing, splitting into words, counting frequencies with Counter, and extracting unique and sorted word lists using sets.
from collections import Counter
def process_text(text):
words = text.lower().split()
word_counts = Counter(words)
unique_words = set(words)
sorted_words = sorted(unique_words)
return {
"total_words": len(words),
"unique_words": len(unique_words),
"word_frequencies": di…
How to Count Words and Find Common Words in Python with Dictionaries and Sets
Build a simple text processor that counts unique words with dictionaries and finds common words across text halves using sets.
def process_text(text):
"""Process text: count unique words with counts, find common words."""
words = text.lower().replace(",", "").replace(".", "").split()
word_counts = {}
for word in words:
word_counts[word] = word_counts.get(word, 0) + 1
total_words = len(words)
unique_wo…
How to Subtract Counters in Python for Bag Differences
Use the Counter class's subtraction operator to compute bag differences, removing items and counts that appear in one multiset but not the other.
from collections import Counter
def subtract_counters(bag1, bag2):
"""Return the difference of two Counters (bag1 - bag2)."""
return bag1 - bag2
if __name__ == "__main__":
inventory = Counter(apples=10, bananas=5, oranges=3)
sold = Counter(apples=4, bananas=2, grapes=2)
remaining = subtract_count…
How to Use ChainMap for Layered Config Lookup in Python
This code demonstrates using collections.ChainMap to combine multiple dictionaries into a single layered lookup, where earlier maps override later ones.
from collections import ChainMap
defaults = {"theme": "light", "lang": "en", "debug": False}
user = {"lang": "de", "auto_save": True}
runtime = {"debug": True}
config = ChainMap(runtime, user, defaults)
if __name__ == "__main__":
print("theme:", config["theme"])
print("lang:", config["lang"])
print("deb…
How to Use Counter for Most Common Elements in Python
This code demonstrates how to find the most frequent elements in a list using Python's Counter class from the collections module.
from collections import Counter
def most_common_elements(items, n=1):
"""Return the n most common elements and their counts."""
counter = Counter(items)
return counter.most_common(n)
if __name__ == "__main__":
data = ["apple", "banana", "apple", "orange", "banana", "apple", "grape"]
print(most_co…
How to Use defaultdict(list) to Group Words by First Letter in Python
This code groups a list of words by their first letter using a defaultdict with a list factory, then prints each group sorted by initial.
from collections import defaultdict
def group_by_initial(words):
groups = defaultdict(list)
for word in words:
groups[word[0].upper()].append(word)
return dict(groups)
if __name__ == "__main__":
words = ["apple", "banana", "apricot", "blueberry", "cherry"]
result = group_by_initial(words)…
Multiset with Counter update and elements in Python
Demonstrates using collections.Counter as a multiset: updating counts with update() and iterating elements() to get repeated items.
from collections import Counter
multiset = Counter(['apple', 'banana', 'apple'])
multiset.update(['banana', 'cherry', 'apple'])
print("Elements after update:", sorted(multiset.elements()))
print("Counts:", dict(multiset))
print("Most common:", multiset.most_common(2))
How to Define Dataclass Field Defaults in Python
Implement a Python dataclass with default values for simple fields and default factories for mutable collections.
from dataclasses import dataclass, field
from typing import List
@dataclass
class Product:
name: str
price: float = 0.0
quantity: int = 0
tags: List[str] = field(default_factory=list)
metadata: dict = field(default_factory=dict)
if __name__ == "__main__":
p1 = Product("Laptop", 999.99, 5)
…
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()
…
Find Single Number Appearing Once in Python
Count frequency of each number in a list and return the one that appears exactly once when all others appear twice.
from collections import Counter
def find_single_number(nums):
counts = Counter(nums)
for num, count in counts.items():
if count == 1:
return num
return None
if __name__ == "__main__":
nums = [4, 1, 2, 1, 2]
result = find_single_number(nums)
print(f"Single number in {nums} …
How to Count Occurrences of Each Value in Python
Count how many times each value appears in a list using Python's Counter from the collections module.
from collections import Counter
def count_occurrences(values):
"""Return a dictionary mapping each value to its count."""
return dict(Counter(values))
if __name__ == "__main__":
sample_data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
result = count_occurrences(sample_data)
print(r…
Count Records Processed per Category in Python
Use a Counter dictionary to track how many records of each type (ok, error, retry) were processed in a data pipeline.
from collections import Counter
import random
processed_counter = Counter()
def process_records(records):
for record in records:
processed_counter[record] += 1
return len(records)
if __name__ == "__main__":
sample_records = [random.choice(["ok", "error", "retry"]) for _ in range(10)]
print(f…
Count Unique Contributors from Git Shortlog in Python
Parses git shortlog -sn output to count the number of unique contributors, handling duplicate entries and variable whitespace.
import subprocess
from collections import Counter
# Mock shortlog output as a list of lines (simulating git shortlog -sn output)
MOCK_SHORTLOG = """ 120 Alice Johnson
88 Bob Smith
45 Alice Johnson
30 Carol Williams
25 Bob Smith
10 Dave Brown
"""
def count_contributors_from_shortlog(text):
"…
Implement a FIFO Message Queue in Python with deque
This code implements a FIFO (first-in-first-out) message queue class using Python's collections.deque, providing enqueue, dequeue, peek, and size operations.
from collections import deque
class MessageQueue:
def __init__(self):
self.queue = deque()
def enqueue(self, message):
self.queue.append(message)
print(f"Enqueued: {message}")
def dequeue(self):
if self.is_empty():
print("Queue is empty, cannot dequeue.")
…
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.