Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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…
How to Implement a Recent Counter with a Deque in Python
Implements a RecentCounter class that uses a deque to count ping requests within the last 3000 milliseconds.
from collections import deque
import time
class RecentCounter:
def __init__(self):
self.hits = deque()
def ping(self, t: int) -> int:
self.hits.append(t)
while self.hits and self.hits[0] < t - 3000:
self.hits.popleft()
return len(self.hits)
if __name__ == "__mai…
Sort Unique Values by Frequency in Python
Count element frequencies with Counter and sort unique values by descending frequency, breaking ties alphabetically.
from collections import Counter
def sort_unique_by_frequency(values):
counts = Counter(values)
return sorted(counts.keys(), key=lambda x: (-counts[x], x))
if __name__ == "__main__":
data = [4, 2, 2, 8, 3, 3, 1, 3, 5, 5, 5, 5, 1]
result = sort_unique_by_frequency(data)
print(f"Sorted unique values…
Count Data in Python with Comprehensions and Generators
Count list items with a dict comprehension and generate squares lazily with a generator expression, printing both results.
from collections import Counter
data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = {item: data.count(item) for item in set(data)}
square_gen = (x * x for x in range(5))
squares = list(square_gen)
if __name__ == "__main__":
print("Manual count:", counts)
print("Counter:", dict(Counter…
Generator Function to Yield an Infinite Counter in Python
This code demonstrates a generator function that yields an infinite sequence of integers starting from a given value, allowing lazy, memory-efficient iteration.
def infinite_counter(start=0):
count = start
while True:
yield count
count += 1
if __name__ == "__main__":
counter = infinite_counter(5)
for _ in range(5):
print(next(counter))
Aggregate Log Errors Count by Hour in Python
Counts ERROR log lines per hour using regex and Counter, returning a sorted dictionary of hourly totals.
import re
from collections import Counter
from datetime import datetime
def aggregate_errors_by_hour(log_lines):
pattern = re.compile(r'^(\d{4}-\d{2}-\d{2} \d{2}):\d{2}:\d{2}.*ERROR')
hourly_counts = Counter()
for line in log_lines:
match = pattern.match(line)
if match:
ho…
Batch Rename Hundreds of Files in Python
Rename all files with a given extension inside a folder using a sequential counter and a custom prefix.
import os
from pathlib import Path
def batch_rename_files(directory: str, prefix: str, extension: str = ".txt") -> None:
"""Rename all files with given extension in directory to prefix_{counter}.ext."""
path = Path(directory)
if not path.is_dir():
print(f"Directory '{directory}' does not exist.")
…
Parse nginx access log top IPs in Python
Reads an nginx access log line by line, extracts the client IP, and returns the most frequent IPs using a regex and Counter.
import re
from collections import Counter
def top_ips(log_file, n=10):
ip_pattern = re.compile(r'^(\S+)')
ip_counts = Counter()
with open(log_file, 'r') as f:
for line in f:
match = ip_pattern.match(line)
if match:
ip_counts[match.group(1)] += 1
return…
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…
How to Make a Git Commit Heatmap by Hour in Python
Parse a git log output and count commits by weekday and hour, then print a compact heatmap table.
import re
from collections import Counter
from datetime import datetime
def parse_commits(log_text):
"""Parse git log lines and count commits by (weekday, hour)."""
pattern = re.compile(r"^Date:\s+(.+)$")
counts = Counter()
for line in log_text.splitlines():
match = pattern.match(line)
…
How to Use ThreadPoolExecutor for Concurrent Tasks in Python
Compare sequential execution with ThreadPoolExecutor for I/O-bound tasks, measuring speedup and timing with perf_counter.
import time
import threading
from concurrent.futures import ThreadPoolExecutor
def fetch_data(index):
"""Simulate a synchronous data fetch."""
time.sleep(0.1)
return f"data-{index}"
def run_sequential(total=10):
"""Run tasks one after another."""
start = time.perf_counter()
results = [fetch…
How to Use asyncio Lock to Protect a Shared Counter in Python
This code demonstrates how to use an asyncio.Lock to safely increment a shared counter from multiple concurrent coroutines.
import asyncio
async def increment(counter, lock, increments):
for _ in range(increments):
async with lock:
counter[0] += 1
async def main():
counter = [0]
lock = asyncio.Lock()
tasks = [
increment(counter, lock, 1000)
for _ in range(5)
]
await asyncio.gath…
How to Use threading.Lock to Synchronize a Counter in Python
Safely increment a shared counter across multiple threads using threading.Lock as a mutex to prevent race conditions.
import threading
counter = 0
lock = threading.Lock()
def increment():
global counter
for _ in range(100000):
with lock:
counter += 1
threads = [threading.Thread(target=increment) for _ in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"Final counter valu…
How to Compare Execution Speed Between Python Functions
Measure and compare the average execution time of multiple Python functions using a reusable benchmark helper with time.perf_counter.
import time
import random
def method_a(values):
"""Sort using built-in sorted."""
return sorted(values)
def method_b(values):
"""Sort using list's sort method."""
values_copy = values[:]
values_copy.sort()
return values_copy
def method_c(values):
"""Sort manually using bubble sort (slow,…
How to Test Hypotheses with Property-Based Check in Python
A Python search that checks an integer property (palindrome divisible by digit sum) and returns the first counterexample within a range, with exactly reproduced output from the code.
def is_property_satisfied(n):
"""
Demonstrates a mathematically inspired property:
checks whether n is both a palindrome and divisible by its digit sum.
"""
s = str(n)
if s != s[::-1]:
return False
digit_sum = sum(int(d) for d in s)
return digit_sum != 0 and n % digit_sum == 0
…
How to Implement a Tumbling Window Counter in Python
Count events that fall within a fixed-size sliding time window using a deque and pruning logic.
from collections import deque
import time
class TumblingWindowCounter:
def __init__(self, window_size_seconds):
self.window_size = window_size_seconds
self.window = deque()
def add_event(self, timestamp):
self.window.append(timestamp)
def count(self, current_time):
while…
Redis INCR DECR Counter Mock in Python
Simulate Redis INCR and DECR commands with a Python class to test counter logic without a live Redis server.
class RedisCounter:
def __init__(self):
self._store = {}
def incr(self, key: str, amount: int = 1) -> int:
if key not in self._store:
self._store[key] = 0
self._store[key] += amount
return self._store[key]
def decr(self, key: str, amount: int = 1) -> int:
…
Refresh Proactive TTL Renewal in Python
This snippet implements a proactive TTL renewal pattern that refreshes a cache expiration before it lapses, using a mock counter to track renewals.
import time
from datetime import datetime, timezone
class TTLRenewer:
def __init__(self, ttl_seconds=10, renew_at=0.5):
self.ttl = ttl_seconds
self.last_renewed = time.time()
self.renew_threshold = ttl_seconds * renew_at
self.renewals = 0
def check_and_renew(self):
if …
Fixed Window Counter Rate Limiting in Python
A simple fixed window counter rate limiter that allows a maximum number of requests per 60-second window, with a mock time simulation.
from collections import deque
from time import time
class FixedWindowCounter:
def __init__(self, max_requests):
self.max_requests = max_requests
self.window_start = int(time())
self.window_count = 0
def allow_request(self):
current_time = int(time())
if current_time >=…
How to Implement a Dead Letter Queue Replay in Python
A mock Dead Letter Queue that stores failed messages with retry attempts and replays them with a simple retry counter.
import json
from collections import deque
class DeadLetterQueue:
def __init__(self):
self.messages = deque()
def add_message(self, message_id, payload, attempts=3):
"""Add a message to the DLQ with retry metadata."""
self.messages.append({
"id": message_id,
…
How to Implement a Sliding Window Counter in Python
This code implements an approximate sliding window counter using a deque of time-based buckets to track event counts within a recent time window.
from collections import deque
from time import time
class SlidingWindowCounter:
def __init__(self, window_size, bucket_size=1):
self.window_size = window_size
self.bucket_size = bucket_size
self.buckets = deque()
def _evict_expired(self, now):
while self.buckets and self.buck…
How to Mock Daily and Monthly Quota Counters in Python
Track daily and monthly API call usage with automatic resets, quota checks, and limits using a Python class.
import random
from datetime import datetime, timedelta
class QuotaCounter:
def __init__(self, daily_limit=1000, monthly_limit=20000):
self.daily_limit = daily_limit
self.monthly_limit = monthly_limit
self.daily_usage = 0
self.monthly_usage = 0
self.current_day = datetime.n…
How to implement a rate-limited shared counter in Python
Implements a thread-safe global counter that allows a maximum number of increments per second using a lock and time-based refill.
import threading
import time
import random
counter = 0
lock = threading.Lock()
MAX_CALLS_PER_SECOND = 3
last_refill = time.time()
def rate_limited_increment():
global counter, last_refill
with lock:
now = time.time()
if now - last_refill >= 1.0:
last_refill = now
count…
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.