Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

42 matches
Algorithms & data structures easy

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.

deque recents sliding-window
Python
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…
11 0 Open
Algorithms & data structures easy

Sort Unique Values by Frequency in Python

Count element frequencies with Counter and sort unique values by descending frequency, breaking ties alphabetically.

counter sorting frequency
Python
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…
12 0 Open
Comprehensions & generators easy

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.

comprehensions generators counter
Python
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…
15 0 Open
Comprehensions & generators easy

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.

generators infinite sequences yield
Python
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))
14 0 Open
Automation & scripting easy

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.

logs regex counter
Python
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…
21 0 Open
Automation & scripting easy

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.

automation files pathlib
Python
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.")
…
57 0 Open
Automation & scripting easy

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.

nginx log parsing regex
Python
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…
14 0 Open
Data pipelines & processing easy

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.

counter metrics data-pipeline
Python
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…
15 0 Open
Concurrency & performance easy

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.

threading lock mutex
Python
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…
14 0 Open
Testing & modern typing easy

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.

hypothesis testing palindrome
Python
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

…
10 0 Open
Streaming & messaging easy

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.

streaming window aggregation
Python
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…
14 0 Open
Caching & Redis easy

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.

redis counter mock
Python
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:
     …
16 0 Open
Reliability & rate limiting easy

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.

rate-limiting fixed-window time
Python
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 >=…
13 0 Open
Reliability & rate limiting easy

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.

dead-letter-queue queue retry
Python
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,
           …
13 0 Open
Reliability & rate limiting easy

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.

sliding-window rate-limiting deque
Python
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…
13 0 Open
Reliability & rate limiting easy

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.

quota rate-limiting class
Python
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…
17 0 Open
Observability & SRE easy

How to Build a Metrics Counter with Increment and Snapshot in Python

A simple dict-backed MetricsCounter class that increments named counters and returns a snapshot of the current values.

metrics counter observability
Python
class MetricsCounter:
    def __init__(self):
        self._metrics = {}

    def increment(self, key, delta=1):
        self._metrics[key] = self._metrics.get(key, 0) + delta

    def snapshot(self):
        return dict(self._metrics)


if __name__ == "__main__":
    counter = MetricsCounter()
    counter.increment("…
13 0 Open
A/B testing & experimentation easy

How to Create a Mock That Returns Inverse Counter Values in Python

Builds a Mock whose side_effect returns the inverse (1/count) of each Counter value, defaulting to 0.0 for unseen keys.

mock counter testing
Python
from collections import Counter
from unittest.mock import Mock

def inverse_mock(counter: Counter) -> Mock:
    """
    Return a Mock that mimics the inverse of a Counter:
    each key returns a value representing the inverse of its count.
    The Mock's side_effect maps keys to their inverse counts.
    """
    mock …
13 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.