Reference library

Python Code Samples

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

47 matches
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
Lists & loops easy

Find Duplicate Elements in a Python List

Identifies and returns duplicate elements from a Python list using sets for efficient membership tests.

duplicates sets list
Python
def find_duplicates(lst):
    seen = set()
    duplicates = set()
    for item in lst:
        if item in seen:
            duplicates.add(item)
        else:
            seen.add(item)
    return list(duplicates)

if __name__ == "__main__":
    sample = [1, 2, 3, 2, 4, 1, 5, 3]
    print(find_duplicates(sample))
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
Lists & loops easy

Intersection of Two Lists Preserving Order in Python

This code returns the common elements between two lists while preserving the order they appear in the first list, filtering out duplicates.

lists intersection order
Python
def intersection_preserving_order(list1, list2):
    """
    Return the intersection of two lists while preserving the order
    of elements as they appear in list1.
    """
    set2 = set(list2)
    result = []
    seen = set()
    
    for item in list1:
        if item in set2 and item not in seen:
            resu…
15 0 Open
Files & data medium

Find Duplicate Web Pages by Content Similarity in Python

Compute SHA-256 hashes of file contents to detect and report duplicate HTML pages or any files in a directory.

duplicate-detection hashing sha256
Python
import hashlib
import os
from collections import defaultdict

def get_file_hash(filepath):
    """Compute SHA-256 hash of file contents."""
    sha256 = hashlib.sha256()
    with open(filepath, 'rb') as f:
        for chunk in iter(lambda: f.read(4096), b''):
            sha256.update(chunk)
    return sha256.hexdiges…
47 0 Open
Files & data medium

How to Find Duplicate Files by Size and Hash in Python

Recursively scan a directory, group files by size, then hash candidates to identify exact duplicate files.

deduplication filesystem hashlib
Python
import hashlib
from pathlib import Path

def hash_file(path, chunk_size=8192):
    hasher = hashlib.md5()
    with open(path, 'rb') as f:
        while chunk := f.read(chunk_size):
            hasher.update(chunk)
    return hasher.hexdigest()

def find_duplicates(directory):
    size_map = {}
    for path in Path(dir…
17 0 Open
Files & data easy

How to Merge Dicts from Two JSON Files Like a Pro

This helper reads two JSON files that contain dicts, merges them with the second file overriding duplicate keys, and saves the result to a new file.

json dict merge
Python
import json
from pathlib import Path


def merge_json_files(file1: str, file2: str, output: str = "merged.json") -> dict:
    """Merge two JSON files containing dicts, with file2 overriding file1."""
    data1 = json.loads(Path(file1).read_text())
    data2 = json.loads(Path(file2).read_text())

    merged = {**data1,…
13 0 Open
Dictionaries & sets easy

Check Invertible Mapping for Duplicate Values in Python

Detect duplicate values among (key, value) pairs to ensure the mapping is invertible, using a dictionary for O(1) lookups.

dictionary mapping duplicate-check
Python
def invertible_after_dedup(pairs):
    """
    Check whether a set of (key, value) pairs is invertible,
    i.e., no duplicate values exist for different keys.
    """
    seen = {}
    for key, value in pairs:
        if value in seen and seen[value] != key:
            return False, f"Duplicate value '{value}' for k…
17 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 Invert a Dictionary in Python Safely

Swap dictionary keys and values while detecting duplicate values to prevent silent data loss.

dictionary inversion data-safety
Python
def invert_dict_safely(d):
    inverted = {}
    for key, value in d.items():
        if value not in inverted:
            inverted[value] = key
        else:
            raise ValueError(f"Duplicate value '{value}' would cause data loss")
    return inverted


if __name__ == "__main__":
    sample = {"a": 1, "b": 2,…
15 0 Open
Dictionaries & sets easy

How to Parse Query String to Dict with Duplicate Keys in Python

Convert a URL query string into a Python dictionary, merging duplicate keys into lists while keeping single values as scalars.

query-string dict url-parsing
Python
from urllib.parse import parse_qs


def parse_query_to_dict(query_string):
    parsed = parse_qs(query_string, keep_blank_values=True)
    return {key: values if len(values) > 1 else values[0] for key, values in parsed.items()}


if __name__ == "__main__":
    query = "name=John&name=Jane&age=30&city=&city=Paris&empty…
13 0 Open
OOP & classes easy

How to Copy Class Instances in Python: Shallow vs Deep Copy

Use copy.copy and copy.deepcopy to clone class instances, showing how nested objects are shared or duplicated.

copy deepcopy shallow copy
Python
import copy


class Config:
    def __init__(self):
        self.settings = {"theme": "dark", "language": "en"}


if __name__ == "__main__":
    original = Config()

    shallow_copy = copy.copy(original)
    deep_copy = copy.deepcopy(original)

    shallow_copy.settings["theme"] = "light"
    deep_copy.settings["them…
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 in One Python List but Not Another

Return a new list containing only the elements from list A that are not present in list B, preserving duplicates and order.

list difference set membership filtering
Python
def difference_elements(a, b):
    """Return elements present in list a but not in list b."""
    set_b = set(b)
    return [item for item in a if item not in set_b]

if __name__ == "__main__":
    a = [1, 2, 3, 4, 5, 3, 2]
    b = [2, 4, 6]
    result = difference_elements(a, b)
    print(f"A: {a}")
    print(f"B: {b…
14 0 Open
Algorithms & data structures easy

Find First Duplicate Index in Python

Return the index of the first element that appears more than once in a list, using a dictionary for O(n) time.

duplicate dictionary arrays
Python
def find_first_duplicate(arr):
    seen = {}
    for index, value in enumerate(arr):
        if value in seen:
            return index
        seen[value] = index
    return -1

if __name__ == "__main__":
    test_array = [3, 5, 2, 8, 5, 1, 2]
    result = find_first_duplicate(test_array)
    print(f"Array: {test_arr…
13 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
Algorithms & data structures medium

Find the Duplicate Number in Python Using Floyd's Cycle Detection

Detects the duplicate integer in an array of n+1 numbers (values 1 to n) in O(n) time and O(1) space using Floyd's cycle detection algorithm applied to a linked-list model.

floyd-cycle duplicate-number two-pointers
Python
def find_duplicate(nums):
    slow = nums[0]
    fast = nums[0]
    
    # Phase 1: Find intersection point of the cycle
    while True:
        slow = nums[slow]
        fast = nums[nums[fast]]
        if slow == fast:
            break
    
    # Phase 2: Find the start of the cycle (the duplicate)
    slow = nums[0…
14 0 Open
Algorithms & data structures medium

How to Find Four Sum Quadruplets in Python (Sorted Demo)

Find all unique quadruplets in a sorted array that sum to a target, with duplicate skipping.

two-pointers sorting four-sum
Python
def four_sum(nums, target):
    nums.sort()
    result = []
    n = len(nums)

    for i in range(n - 3):
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        for j in range(i + 1, n - 2):
            if j > i + 1 and nums[j] == nums[j - 1]:
                continue
            left, right = j + 1…
13 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

Simplify a File Path in Python with a Stack

Uses a stack to normalize an absolute Unix path by handling '.', '..', and duplicate slashes.

stack string path
Python
from pathlib import PurePosixPath

def simplify_path(path: str) -> str:
    tokens = path.split('/')
    stack = []
    
    for token in tokens:
        if not token or token == '.':
            continue
        if token == '..':
            if stack:
                stack.pop()
        else:
            stack.append…
11 0 Open
Comprehensions & generators easy

Python Generator to Filter Duplicates with a Seen Set

A lazily-evaluated generator function that yields only the first occurrence of each item, using a set to track seen values.

generator dedupe set
Python
def unique_generator(items):
    seen = set()
    for item in items:
        if item not in seen:
            seen.add(item)
            yield item

if __name__ == "__main__":
    data = [1, 2, 2, 3, 3, 3, 4, 5, 5]
    result = list(unique_generator(data))
    print(result)
14 0 Open
Automation & scripting medium

Find and Delete Duplicate Files Using Hashing in Python

Walk a directory tree, compute SHA256 hashes for every file, and delete duplicates that share the same hash.

deduplication files hashing
Python
import hashlib
import os
from pathlib import Path

def file_hash(path, block_size=65536):
    """Return SHA256 hash of file content."""
    hasher = hashlib.sha256()
    with open(path, 'rb') as f:
        while chunk := f.read(block_size):
            hasher.update(chunk)
    return hasher.hexdigest()

def find_and_d…
51 0 Open
Automation & scripting easy

How to Hash Duplicate Photos and Delete Copies in Python

This script hashes image files in a directory using SHA-256 and deletes duplicate copies while keeping the first occurrence, ideal for cleaning up photo libraries.

hashlib deduplication file-automation
Python
from pathlib import Path
import hashlib

def file_hash(path, chunk_size=8192):
    hasher = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(chunk_size), b""):
            hasher.update(chunk)
    return hasher.hexdigest()

def delete_duplicate_photos(directory):
    directory …
14 0 Open
Data pipelines & processing medium

Build a Python Utility That Detects Duplicate Records Across Multiple Excel Sheets

A Python utility that uses pandas to find overlapping records across different Excel sheets based on specified key columns.

pandas excel data cleaning
Python
import pandas as pd
from pathlib import Path

def find_duplicate_records_across_sheets(file_path: str, key_columns: list, sheet_names: list) -> dict:
    """
    Detect duplicate records across multiple Excel sheets based on specified key columns.
    
    Args:
        file_path: Path to the Excel file
        key_co…
46 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.