Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

55 matches
Strings & text easy

Count Characters, Words, and Lines in Python Text

Counts characters, words, lines, and the most common words in a given string using Python's standard library.

text-analysis counter strings
Python
from collections import Counter


def count_data(text):
    """Count characters, words, lines, and most common words in text."""
    char_count = len(text)
    word_count = len(text.split())
    line_count = text.count("\n") + 1
    word_freq = Counter(text.lower().split())
    most_common = word_freq.most_common(3)

…
17 0 Open
Lists & loops easy

Find Most Active Contributors in a Repository with Python

Filter recent commits by date and count the most active contributors using Counter and datetime.

collections datetime counter
Python
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…
45 0 Open
Lists & loops easy

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.

counter frequency dictionary
Python
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…
13 0 Open
Lists & loops easy

How to Count Occurrences of a Value in a Python List

Counts how many times a specific value appears in a list using a simple loop and a counter variable.

counting loops lists
Python
def count_occurrences(data, target):
    count = 0
    for item in data:
        if item == target:
            count += 1
    return count


if __name__ == "__main__":
    numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
    target_value = 5
    result = count_occurrences(numbers, target_value)
    print(f"The value {targ…
13 0 Open
Lists & loops easy

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.

mode counter frequency
Python
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__":
    …
14 0 Open
Functions & basics easy

How to Count Items with Default Parameters in Python

Define a Python function that prints each item with a running counter, using default parameters to allow custom start values and step increments.

functions default-parameters loops
Python
def count_items(items, start=0, step=1):
    """Count items in a list with configurable start value and step."""
    count = start
    for item in items:
        print(f"{count}: {item}")
        count += step

if __name__ == "__main__":
    fruits = ["apple", "banana", "cherry"]
    print("Default parameters (start=0…
11 0 Open
Functions & basics medium

How to Create a Counter Closure in Python

Build a closure in Python that remembers and increments a counter across calls without using global variables.

closures nonlocal state
Python
def create_counter(start=0):
    count = start
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

if __name__ == "__main__":
    counter = create_counter(10)
    print(counter())
    print(counter())
    print(counter())
12 0 Open
Functions & basics easy

How to Create a Timing Decorator in Python

A Python decorator that measures and prints the execution time of any function using time.perf_counter.

decorator timing perf_counter
Python
import time
from functools import wraps


def timing_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        end = time.perf_counter()
        elapsed = end - start
        print(f"{func.__name__} took {elapsed:.6f} seconds"…
11 0 Open
Functions & basics easy

How to Create an Iterator Class with Dunder Methods in Python

A minimal Counter class implementing __iter__ and __next__ to act as a self-iterating iterator, yielding numbers from start to end-1.

iterators dunder-methods class
Python
class Counter:
    def __init__(self, start=0, end=5):
        self.current = start
        self.end = end

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.end:
            raise StopIteration
        value = self.current
        self.current += 1
        return val…
13 0 Open
Files & data easy

How to Extract IP Address Counts from Access Logs in Python

Read a web server access log, count occurrences of each IP address using regex and Counter, and print the ranked results.

regex access log counter
Python
import re
from collections import Counter
from pathlib import Path

def extract_ip_counts(log_file_path):
    ip_pattern = r'^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
    ip_counter = Counter()
    
    with open(log_file_path, 'r') as file:
        for line in file:
            match = re.match(ip_pattern, line)
       …
17 0 Open
Dictionaries & sets easy

Count Word Frequency in Python with dict

Count how often each word appears in a text using Python's collections.Counter and regular expressions.

dictionary counter frequency
Python
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 …
13 0 Open
Dictionaries & sets easy

Count word frequency in Python with dict and Counter

Count how often each word appears in a string using Counter, converted to a plain dict, and print results alphabetically.

counter dictionary word-frequency
Python
from collections import Counter
import re

def count_word_frequency(text):
    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 dog barks, and the fox runs."
    frequency = count_word_frequency(…
12 0 Open
Dictionaries & sets easy

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.

counter dict sorting
Python
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("…
13 0 Open
Dictionaries & sets easy

How to Count Co-occurrence Pairs in Python with Nested Dictionaries

This code counts how often any two items appear together in the same group, using a nested defaultdict keyed by item pairs.

dictionaries co-occurrence counter
Python
from itertools import combinations
from collections import defaultdict

def count_cooccurrences(items_per_group):
    cooccurrence = defaultdict(lambda: defaultdict(int))
    for group in items_per_group:
        for a, b in combinations(sorted(group), 2):
            cooccurrence[a][b] += 1
            cooccurrence[b…
12 0 Open
Dictionaries & sets easy

How to Count Elements and Find Duplicates in a Python List

Count occurrences of each element in a list, extract unique values, and identify duplicates using Python dictionaries and sets.

dictionary set counting
Python
def analyze_counts(data):
    """Count elements, return unique values, and find duplicates."""
    
    # Count occurrences using a dictionary
    counts = {}
    for item in data:
        counts[item] = counts.get(item, 0) + 1
    
    # Alternative compact approach with set
    unique_items = set(data)
    
    # Fi…
12 0 Open
Dictionaries & sets easy

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.

collections counter sets
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…
11 0 Open
Dictionaries & sets easy

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.

counter sets text-processing
Python
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…
12 0 Open
Dictionaries & sets easy

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.

collections counter bags
Python
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…
14 0 Open
Dictionaries & sets easy

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.

collections counter frequency
Python
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…
13 0 Open
Dictionaries & sets easy

How to Use Dictionaries and Sets in Python for Beginners

Introduces Python dictionaries and sets with practical examples including creating, modifying, and performing set operations, plus a word-frequency counter.

dictionaries sets data structures
Python
def demonstrate_dict_sets():
    # Create a dictionary with basic info
    person = {
        "name": "Alice",
        "age": 30,
        "city": "New York"
    }
    print("Dictionary:", person)

    # Access and modify dictionary values
    person["age"] = 31
    person["email"] = "alice@example.com"
    print("Afte…
15 0 Open
Dictionaries & sets easy

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.

counter multiset collections
Python
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))
13 0 Open
Algorithms & data structures easy

Find Common Elements in List of Lists in Python

Return elements that appear in every sublist of a nested list, preserving duplicates with Counter intersection.

counter intersection nested-lists
Python
from collections import Counter


def common_elements(list_of_lists):
    """Return elements present in every sublist."""
    if not list_of_lists:
        return []
    counts = Counter(list_of_lists[0])
    for sublist in list_of_lists[1:]:
        counts &= Counter(sublist)
    return list(counts.elements())


if _…
13 0 Open
Algorithms & data structures easy

Find Elements Appearing More Than n/3 Times in Python

Return all elements that occur more than len(array)/3 times using a simple dictionary counter.

majority-element dictionary counting
Python
def majority_third(arr):
    """Return elements appearing more than len(arr)/3 times."""
    cutoff = len(arr) / 3
    counts = {}
    for x in arr:
        counts[x] = counts.get(x, 0) + 1
    return [x for x, c in counts.items() if c > cutoff]


if __name__ == "__main__":
    test1 = [3, 2, 3]
    test2 = [1, 1, 1, …
11 0 Open
Algorithms & data structures medium

Find Missing Numbers, Duplicates, and Ranges in Python

Analyze a list to identify missing numbers, duplicate values, and contiguous ranges using sets and the Counter class.

algorithms sets counting
Python
def find_missing_duplicates_ranges(numbers):
    """Find missing numbers, duplicates, and ranges in a list."""
    from collections import Counter
    
    if not numbers:
        return {"missing": [], "duplicates": [], "ranges": []}
    
    full_range = set(range(min(numbers), max(numbers) + 1))
    present = set(n…
12 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.