Reference library

Python Code Samples

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

258 matches
Strings & text easy

Automatically Detect Weak Passwords from Large Password Lists in Python

This Python script identifies weak passwords from a list by checking length, common patterns, sequential characters, and uniform characters, returning those that fail the security checks.

password security validation
Python
import re

COMMON_PASSWORDS_FILE = "common_passwords.txt"

def is_weak(password):
    # Check length
    if len(password) < 8:
        return True
    # Check for common patterns
    if password.lower() in {"password", "123456", "qwerty", "letmein", "admin", "welcome"}:
        return True
    # Check for sequential c…
54 0 Open
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…
13 0 Open
Strings & text easy

How to Compare Two Strings in Python

Compares two string values and returns a detailed report with equality, case-insensitive comparison, lengths, and uppercase versions.

string-comparison case-insensitive helper-function
Python
def compare_data(first_value, second_value):
    """Compare two string values and return a report."""
    if first_value == second_value:
        status = "MATCH"
    else:
        status = "DIFFER"
    return {
        "first_value": first_value,
        "second_value": second_value,
        "status": status,
       …
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

How to Remove Duplicate Adjacent Spaces in Python

This Python function collapses any sequence of two or more adjacent spaces into a single space, preserving all other characters.

strings whitespace text-cleaning
Python
def remove_duplicate_adjacent_spaces(text):
    """Replace sequences of 2+ spaces with a single space."""
    result = []
    prev_was_space = False
    for char in text:
        if char == " ":
            if not prev_was_space:
                result.append(char)
            prev_was_space = True
        else:
     …
12 0 Open
Strings & text easy

How to build a text helper in Python for beginners

This code provides easy-to-use functions for cleaning text, removing punctuation, counting word frequencies, and summarizing strings — perfect for beginners.

string-manipulation text-processing word-count
Python
def clean_text(text: str) -> str:
    """Clean and normalize a text string."""
    text = text.strip()
    text = text.replace("  ", " ")
    text = text.capitalize()
    text = text.replace(".", ".")
    return text


def remove_punctuation(text: str) -> str:
    """Remove common punctuation marks from a string."""
 …
12 0 Open
Strings & text easy

Normalize unicode accents to ASCII in Python

This code converts accented Unicode characters to ASCII equivalents using the standard library's unicodedata module.

unicode accents normalization
Python
import unicodedata

def normalize_accents(text: str) -> str:
    """Convert accented unicode characters to ASCII equivalents."""
    decomposed = unicodedata.normalize('NFD', text)
    ascii_text = ''.join(
        char for char in decomposed
        if unicodedata.category(char) != 'Mn'
    )
    return unicodedata.n…
14 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

Check if List is Sorted Ascending in Python

Verify that a list is sorted in ascending order using the all() function and a generator expression.

lists sorted all
Python
def is_sorted_ascending(lst):
    return all(lst[i] <= lst[i + 1] for i in range(len(lst) - 1))

if __name__ == "__main__":
    test_lists = [
        [1, 2, 3, 4, 5],
        [1, 3, 2, 4, 5],
        [5, 4, 3, 2, 1],
        [1, 1, 2, 2, 3],
        [10],
        []
    ]
    for lst in test_lists:
        print(f"{l…
19 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 Calculate a Cumulative Sum in Python

Build a new list where each element equals the running total of all numbers up to that index in the original list.

lists cumulative-sum loops
Python
numbers = [1, 2, 3, 4, 5]
cumulative_sum = []
running_total = 0

for num in numbers:
    running_total += num
    cumulative_sum.append(running_total)

print(cumulative_sum)
12 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
Lists & loops easy

How to Group Consecutive Equal Elements in Python

Group consecutive equal elements in a list into sublists using itertools.groupby.

groupby itertools lists
Python
from itertools import groupby

def group_consecutive(lst):
    """Group consecutive equal elements into sublists."""
    return [list(group) for _, group in groupby(lst)]

if __name__ == "__main__":
    input_list = [1, 1, 2, 2, 2, 3, 1, 1, 4, 4, 4, 4]
    result = group_consecutive(input_list)
    print("Input:", inp…
16 0 Open
Lists & loops easy

How to Partition a List Around a Pivot in Python

This code splits a list into three parts—elements less than, equal to, and greater than a pivot—then concatenates them to produce a partitioned list while preserving the original order within each group.

partition list pivot
Python
def partition_list(lst, pivot):
    less = []
    equal = []
    greater = []
    for item in lst:
        if item < pivot:
            less.append(item)
        elif item == pivot:
            equal.append(item)
        else:
            greater.append(item)
    return less + equal + greater

if __name__ == "__main__…
14 0 Open
Lists & loops easy

Truncate List Keeping Last N Elements in Python

Return a new list containing only the last N elements from a sequence, handling edge cases like zero or oversized counts.

list slicing sequence
Python
def truncate(seq, keep_last_n):
    """Return a new list keeping only the last n elements."""
    if keep_last_n <= 0:
        return []
    return list(seq)[-keep_last_n:]


if __name__ == "__main__":
    data = [10, 20, 30, 40, 50, 60]
    print(truncate(data, 3))
    print(truncate(data, 0))
    print(truncate(data…
11 0 Open
Functions & basics easy

Chain Generators with yield from in Python

Combine multiple generators into one seamless sequence using the `yield from` delegation syntax in Python.

generators yield delegation
Python
def numbers():
    yield 1
    yield 2
    yield 3

def letters():
    yield 'a'
    yield 'b'
    yield 'c'

def combined():
    yield from numbers()
    yield from letters()

if __name__ == "__main__":
    print(list(combined()))
16 0 Open
Functions & basics easy

How to Convert a List to an Iterator in Python with iter()

This code converts a list into an iterator using the built-in iter() function and retrieves items sequentially with next(), handling exhaustion with StopIteration.

iter iterator built-in
Python
def main():
    # Original list
    fruits = ["apple", "banana", "cherry"]

    # Convert the list to an iterator using iter()
    fruit_iterator = iter(fruits)

    # Retrieve items one at a time with next()
    print(next(fruit_iterator))  # apple
    print(next(fruit_iterator))  # banana
    print(next(fruit_iterat…
12 0 Open
Functions & basics easy

How to Create Generator Functions with yield in Python

Create a memory-efficient generator function using yield to produce a Fibonacci sequence up to a limit.

generator yield fibonacci
Python
def fibonacci_sequence(limit):
    """Generate Fibonacci numbers up to a given limit."""
    a, b = 0, 1
    while a <= limit:
        yield a
        a, b = b, a + b


if __name__ == "__main__":
    fib_gen = fibonacci_sequence(100)
    
    for number in fib_gen:
        print(number, end=" ")
    print()
11 0 Open
Functions & basics easy

How to Pipe Data Through a List of Transform Functions in Python

Applies a sequence of functions to an initial value using functools.reduce, creating a reusable pipe utility.

functions functional reduce
Python
from functools import reduce

def pipe(data, *transforms):
    return reduce(lambda value, func: func(value), transforms, data)

def double(x):
    return x * 2

def add_one(x):
    return x + 1

def to_string(x):
    return f"Result: {x}"

if __name__ == "__main__":
    initial = 5
    result = pipe(initial, double, …
13 0 Open
Functions & basics easy

How to Use Default Parameters in Python Functions

A beginner-friendly Python function that uses default parameters to compare two numbers with equal, greater, or less operations.

functions default-parameters comparison
Python
def compare(a, b, operation="equal"):
    if operation == "equal":
        return a == b
    elif operation == "greater":
        return a > b
    elif operation == "less":
        return a < b
    else:
        return f"Unknown operation: {operation}"

if __name__ == "__main__":
    print(compare(5, 5))
    print(com…
13 0 Open
Errors & debugging medium

How to Add a Correlation ID to Logging Records in Python

Attach a unique correlation ID to every log record using a custom logging.Filter, making distributed request tracking traceable.

logging correlation-id filter
Python
import logging
import uuid
from dataclasses import dataclass, field


@dataclass
class CorrelationIdFilter(logging.Filter):
    correlation_id: str = field(default_factory=lambda: str(uuid.uuid4()))

    def filter(self, record: logging.LogRecord) -> bool:
        record.correlation_id = self.correlation_id
        re…
15 0 Open
Errors & debugging easy

How to Mock a Failing Dependency to Test Error Paths in Python

Inject a fake HTTP client that raises a connection error to test how code handles dependency failures without touching the network.

testing mocking requests
Python
import requests

def fetch_user(user_id):
    url = f"https://api.example.com/users/{user_id}"
    response = requests.get(url, timeout=5)
    response.raise_for_status()
    return response.json()

def get_user_name(user_id, http_client):
    try:
        user_data = http_client(user_id)
        return user_data["nam…
16 0 Open
Errors & debugging easy

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.

ring-buffer deque error-handling
Python
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)
 …
13 0 Open
Errors & debugging medium

How to attach a request ID to exception messages in Python

This code shows how to enrich exception messages with contextual request IDs using context variables, making error logs more traceable across concurrent requests.

contextvars exception-handling logging
Python
import logging
from contextvars import ContextVar

request_id_var = ContextVar("request_id", default="unknown")

def add_request_id(exc: Exception) -> Exception:
    exc.args = (f"request_id={request_id_var.get()} | {exc.args[0]}" if exc.args else f"request_id={request_id_var.get()}",) + exc.args[1:]
    return exc

d…
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.