Reference library

Python Code Samples

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

15 matches
Strings & text easy

Find Most Frequent Character in a String in Python

Count character frequencies in a Python string using a dictionary and return the character that appears most often with a max() key function.

string dictionary counting
Python
def most_frequent_char(s: str) -> str:
    if not s:
        return ""
    
    char_count = {}
    for ch in s:
        char_count[ch] = char_count.get(ch, 0) + 1
    
    max_char = max(char_count, key=char_count.get)
    return max_char

if __name__ == "__main__":
    text = "programming"
    result = most_frequent…
12 0 Open
Strings & text easy

How to Parse and Clean Text in Python

This code defines three helper functions to parse text into lowercase words, count unique word frequencies, and clean text by removing punctuation and extra whitespace.

text parsing string cleaning word frequency
Python
def extract_words(text: str) -> list[str]:
    """Return a list of lowercase words from the given text."""
    return [word.lower() for word in text.split() if word.isalpha()]


def count_unique_words(text: str) -> dict[str, int]:
    """Return a dictionary with unique words and their frequencies."""
    words = extra…
11 0 Open
Strings & text easy

Python String Helper Functions for Beginners

A set of beginner-friendly Python functions that count words, reverse text, convert to title case, strip punctuation, and compute character frequency from a string.

strings text-processing word-count
Python
def count_words(text):
    """Count the number of words in a string."""
    return len(text.split())


def reverse_text(text):
    """Reverse the entire string."""
    return text[::-1]


def title_case(text):
    """Capitalize the first letter of each word."""
    return text.title()


def remove_punctuation(text):
 …
14 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 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
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 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 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
Algorithms & data structures easy

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.

counter frequency single-number
Python
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} …
13 0 Open
Algorithms & data structures easy

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.

counter counting collections
Python
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…
10 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
Caching & Redis medium

How to Implement an LFU Cache in Python

Implement a Least Frequently Used (LFU) cache with frequency tracking dictionaries to evict the least accessed items when capacity is reached.

lfu cache frequency
Python
class LFUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.data = {}
        self.freq = {}
        self.min_freq = 0

    def get(self, key: int) -> int:
        if key not in self.data:
            return -1
        self._increment_freq(key)
        return self.data[key]

  …
12 0 Open
Big data & Spark easy

How to Implement MapReduce Word Count in Python Using a Dict

Simulate a MapReduce word count pipeline in Python with a mock dict, splitting text into words, shuffling, and reducing to frequency counts.

mapreduce word-count dictionary
Python
def map_reduce_word_count(text: str) -> dict:
    """Simulate a MapReduce pipeline to count word frequencies."""
    # MAP phase: split into words and emit (word, 1) pairs
    mapped = []
    for word in text.lower().split():
        # Clean word of punctuation
        clean_word = ''.join(char for char in word if cha…
16 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.