Reference library

Python Code Samples

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

34 matches
Strings & text easy

How to Extract Digits Only from a String in Python

This code uses a regular expression to remove all non-digit characters from a mixed string, returning only the digits.

regex string manipulation data cleaning
Python
import re

def extract_digits(text):
    """Return only the digits from the given text as a string."""
    return re.sub(r'\D', '', text)

if __name__ == "__main__":
    mixed = "abc123def456!@#789"
    result = extract_digits(mixed)
    print(result)
12 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 Remove HTML Tags in Python with Regex

Strips all HTML tags from a string using a regular expression and cleans extra whitespace.

regex html text-cleaning
Python
import re

def remove_html_tags(text: str) -> str:
    """Remove all HTML tags from the given text using regex."""
    # Remove opening and closing tags
    clean = re.sub(r'<[^>]+>', '', text)
    # Remove any extra whitespace left behind
    clean = re.sub(r'\s+', ' ', clean).strip()
    return clean

if __name__ ==…
12 0 Open
Strings & text easy

How to Strip Whitespace in Python

This code demonstrates how to remove leading and trailing whitespace from a string using the built-in strip() method.

string whitespace text-cleaning
Python
def strip_whitespace(text: str) -> str:
    return text.strip()

if __name__ == "__main__":
    sample = "   Hello, world!   "
    result = strip_whitespace(sample)
    print(f"Original: '{sample}'")
    print(f"Stripped: '{result}'")
14 0 Open
Strings & text easy

How to remove punctuation from a string in Python

Remove all punctuation characters from a string using the str.translate method and string.punctuation from the standard library.

string punctuation translate
Python
import string

def remove_punctuation(text: str) -> str:
    return text.translate(str.maketrans("", "", string.punctuation))

if __name__ == "__main__":
    sample = "Hello, world! It's a test... (with punctuation) - done?"
    cleaned = remove_punctuation(sample)
    print(f"Original: {sample}")
    print(f"Cleaned:…
14 0 Open
Strings & text easy

Remove Substring Occurrences Case-Insensitively in Python

This code removes every case-insensitive occurrence of a given substring from a text string using a simple looping approach.

strings case-insensitive substring
Python
def remove_occurrences_ci(text: str, substring: str) -> str:
    """Remove all case-insensitive occurrences of substring from text."""
    if not substring:
        return text
    
    result = []
    i = 0
    lower_text = text.lower()
    lower_sub = substring.lower()
    sub_len = len(substring)
    
    while i <…
12 0 Open
Strings & text easy

String helpers in Python: stats, reverse, and remove vowels

Three beginner-friendly Python functions compute text statistics, reverse word order, and strip vowels from a string.

string-manipulation text-stats vowel-removal
Python
def text_stats(text: str) -> dict:
    """Return basic statistics for a given text string."""
    words = text.split()
    return {
        "characters": len(text),
        "words": len(words),
        "sentences": text.count(".") + text.count("!") + text.count("?"),
        "uppercase": sum(1 for c in text if c.isupp…
14 0 Open
Lists & loops easy

How to Filter Empty Strings in Python

Remove empty and whitespace-only strings from a list using a list comprehension with the strip() method.

filtering strings list-comprehension
Python
def filter_empty_strings(strings):
    """
    Filter out empty strings (including whitespace-only strings)
    from a list of strings.
    """
    return [s for s in strings if s.strip()]


if __name__ == "__main__":
    sample_list = ["hello", "", "world", "   ", "python", " ", "!"]
    filtered = filter_empty_strin…
12 0 Open
Lists & loops easy

How to Get the Union of Two Lists Without Duplicates in Python

Merge two lists and remove duplicate values using a set, then convert back to a list.

set union merge
Python
def union_without_duplicates(list1, list2):
    return list(set(list1 + list2))

if __name__ == "__main__":
    list_a = [1, 2, 3, 4]
    list_b = [3, 4, 5, 6]
    result = union_without_duplicates(list_a, list_b)
    print(f"Union of {list_a} and {list_b}: {result}")
13 0 Open
Errors & debugging medium

How to Diff Two Dicts in Python for Config Drift

Recursively compare two dictionaries and report added, removed, and changed keys with their old and new values for debugging configuration drift.

dict diff config
Python
def diff_dicts(a, b, path=""):
    differences = []

    for key in a.keys() | b.keys():
        new_path = f"{path}.{key}" if path else key

        if key not in a:
            differences.append((new_path, "<missing>", b[key], "added"))
        elif key not in b:
            differences.append((new_path, a[key], "<…
12 0 Open
Files & data easy

Build a Python Script That Detects and Deletes Empty Files Across Folders

A Python script that recursively finds and removes all zero-byte files across nested directories, returning a list of deleted paths.

filesystem cleanup pathlib
Python
import os
from pathlib import Path

def find_and_delete_empty_files(root_dir: str) -> list:
    """Find and delete all empty files under root_dir. Returns list of deleted paths."""
    deleted = []
    for file_path in Path(root_dir).rglob('*'):
        if file_path.is_file() and file_path.stat().st_size == 0:
       …
56 0 Open
Files & data easy

How to Prune Empty Directories in Python with os.walk

Remove all empty subdirectories bottom-up using os.walk with topdown=False and os.rmdir, safely ignoring non-empty folders.

os.walk filesystem cleanup
Python
import os

def prune_empty_dirs(root):
    """Remove all empty subdirectories under root, bottom-up."""
    for dirpath, dirnames, filenames in os.walk(root, topdown=False):
        if dirpath == root:
            continue
        try:
            os.rmdir(dirpath)
            print(f"Removed: {dirpath}")
        exce…
14 0 Open
Dictionaries & sets easy

How to Diff Two Dicts in Python: Added, Removed, and Changed Keys

Compare two dictionaries and report added, removed, and changed keys using Python's set operations on dict keys.

dict diff set-operations
Python
def diff_dicts(old: dict, new: dict) -> dict:
    """Compare two dicts and report added, removed, and changed keys."""
    added = {k: new[k] for k in new.keys() - old.keys()}
    removed = {k: old[k] for k in old.keys() - new.keys()}

    common_keys = old.keys() & new.keys()
    changed = {k: (old[k], new[k]) for k …
15 0 Open
Dictionaries & sets medium

How to Recursively Remove None Values from Nested Dictionaries in Python

Recursively removes all None values from nested dictionaries and lists while preserving non-None data.

dictionaries recursion data-cleaning
Python
def prune_none(obj):
    if isinstance(obj, dict):
        return {
            k: prune_none(v)
            for k, v in obj.items()
            if v is not None and prune_none(v) is not None
        }
    elif isinstance(obj, list):
        pruned = [prune_none(item) for item in obj]
        pruned = [item for item i…
15 0 Open
Dictionaries & sets easy

How to Remove Banned Words from a Set in Python

Filter a vocabulary set by removing banned words using the .difference() method.

sets set difference filtering
Python
vocabulary = {"apple", "banana", "cherry", "date", "elderberry"}
banned_words = {"banana", "date", "fig"}

# Remove banned words using set difference
allowed_words = vocabulary.difference(banned_words)

print("Original vocabulary:", sorted(vocabulary))
print("Banned words:", sorted(banned_words))
print("Allowed words …
16 0 Open
OOP & classes easy

Graph Class with Adjacency Dict in Python

Build an undirected graph class using a dictionary of adjacency lists with methods to add vertices, edges, remove edges, and query neighbors.

graph oop adjacency-list
Python
class Graph:
    def __init__(self):
        self.adjacency = {}

    def add_vertex(self, vertex):
        if vertex not in self.adjacency:
            self.adjacency[vertex] = []

    def add_edge(self, u, v):
        self.add_vertex(u)
        self.add_vertex(v)
        self.adjacency[u].append(v)
        self.adja…
12 0 Open
OOP & classes medium

How to Build a Linked List Node Class in Python

Create a Node class and a LinkedList class with insert, remove, and display methods to manage a singly linked list.

linked-list node oop
Python
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def insert(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
        else:
            current = self.…
12 0 Open
OOP & classes easy

How to Count Items in a Python Class

A beginner-friendly Inventory class that stores item quantities in a dictionary and provides add, remove, count, and summary methods.

oop classes inventory
Python
class Inventory:
    def __init__(self):
        self.items = {}

    def add(self, item, quantity=1):
        self.items[item] = self.items.get(item, 0) + quantity

    def remove(self, item, quantity=1):
        if item not in self.items:
            raise ValueError(f"{item} not in inventory")
        self.items[it…
13 0 Open
Algorithms & data structures easy

How to Remove Banned Values from a List in Python

Filters a list by removing elements present in a banned set, preserving the original order.

list set filter
Python
def remove_banned(values, banned):
    banned_set = set(banned)
    return [item for item in values if item not in banned_set]


if __name__ == "__main__":
    values = [1, 2, 3, 4, 5, 2, 6, 3, 7]
    banned = [2, 3]
    result = remove_banned(values, banned)
    print(result)
12 0 Open
Algorithms & data structures easy

How to Remove Duplicates in Python Preserving Order

Removes duplicate items from a list while keeping the first occurrence order intact using a set for fast membership checks.

deduplication set list
Python
def remove_duplicates_preserving_order(items):
    seen = set()
    result = []
    for item in items:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

if __name__ == "__main__":
    sample = [3, 1, 2, 1, 3, 4, 2, 5]
    unique_items = remove_duplicates_preserv…
14 0 Open
Algorithms & data structures easy

Remove item at index without pop in Python

Remove an item at a given index from a list without using pop by slicing the list around the index.

list slicing algorithms
Python
def remove_at_index(lst, index):
    """Remove item at index and return the new list."""
    if index < 0 or index >= len(lst):
        raise IndexError("Index out of range")
    return lst[:index] + lst[index + 1:]


if __name__ == "__main__":
    items = [10, 20, 30, 40, 50]
    result = remove_at_index(items, 2)
  …
12 0 Open
Automation & scripting medium

Detect and Remove Blurry Images in Python with OpenCV

Automatically scan a directory of images, detect blur using Laplacian variance, and remove blurry images with a dry-run option for safety.

opencv image-processing automation
Python
from pathlib import Path
import cv2
import numpy as np

def is_blurry(image_path, threshold=100.0):
    """
    Detect if an image is blurry using Laplacian variance.
    Returns True if blurry, False otherwise.
    """
    img = cv2.imread(str(image_path), cv2.IMREAD_GRAYSCALE)
    if img is None:
        return True…
48 0 Open
Automation & scripting medium

How to Detect Network Interface Changes in Python

Monitor active network interfaces and print a message when an interface is added or removed using psutil and socket.

network monitoring psutil
Python
import socket
import psutil
import time

def get_network_interfaces():
    """Return a set of currently active interface names."""
    active_ifaces = set()
    for iface, addrs in psutil.net_if_addrs().items():
        for addr in addrs:
            if addr.family == socket.AF_INET:  # IPv4 address present
          …
42 0 Open
Automation & scripting easy

How to Strip EXIF Metadata from Images in Python

Remove EXIF metadata from image bytes using Pillow, with a mock JPEG generator for testing.

exif images metadata
Python
from PIL import Image
from PIL.ExifTags import TAGS
from io import BytesIO
import struct

def strip_exif(image_bytes, remove_metadata=True):
    """Remove EXIF metadata from image bytes."""
    img = Image.open(BytesIO(image_bytes))
    if remove_metadata:
        # Clear all metadata
        img.info.clear()
    # Sa…
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.