Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

18 matches
Strings & text easy

Find the Index of a Substring or Return a Default in Python

Finds the index of a substring using str.find() and returns a specified default value instead of -1 when the substring is not found.

substring string-index str-find
Python
def find_substring_or_default(text, substring, default=-1):
    index = text.find(substring)
    return index if index != -1 else default

if __name__ == "__main__":
    text = "The quick brown fox jumps over the lazy dog"
    print(find_substring_or_default(text, "brown"))
    print(find_substring_or_default(text, "c…
13 0 Open
Strings & text easy

How to Filter a List of Strings by Keyword in Python

A helper function filters a list of strings by a keyword search with optional case sensitivity.

string filter list
Python
def filter_strings(items, keyword, case_sensitive=False):
    """
    Filter a list of strings by a keyword.
    
    Args:
        items: list of strings to filter
        keyword: substring to search for
        case_sensitive: if True, match case exactly
    
    Returns:
        list of strings containing the keyw…
12 0 Open
Strings & text easy

How to Highlight Search Terms in Python Text

Highlights all case-insensitive occurrences of a search term in a string by wrapping them in markers.

string search highlight
Python
def highlight_search_term(text: str, term: str) -> str:
    """Highlight all occurrences of term in text using terminal-style markers."""
    if not term:
        return text

    term_lower = term.lower()
    result = []
    i = 0

    while i < len(text):
        # Check if the term starts at position i (case-insens…
11 0 Open
Lists & loops easy

Find All Occurrences of an Item in a Python List

Loop through a list with enumerate() to collect the index of every match for a target value.

list enumerate loops
Python
def find_all(data, target):
    """Return indices of every occurrence of target in a list."""
    indices = []
    for index, item in enumerate(data):
        if item == target:
            indices.append(index)
    return indices


if __name__ == "__main__":
    sample = [10, 20, 30, 20, 40, 20, 50]
    target_value …
14 0 Open
Functions & basics easy

How to implement binary search in Python

Standalone binary search function that returns the index of a target in a sorted list, or -1 if not found.

binary search algorithms search
Python
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    
    return -1

if __name__ ==…
13 0 Open
Files & data easy

Create a Personal Knowledge Base That Searches Notes Instantly in Python

Build a lightweight personal knowledge base with JSON storage and instant case-insensitive full-text search across note titles and content.

json knowledge base search
Python
import json
import re
import sys

class PersonalKnowledgeBase:
    def __init__(self, file_path="kb_notes.json"):
        self.file_path = file_path
        self.notes = self._load_notes()

    def _load_notes(self):
        try:
            with open(self.file_path, "r") as f:
                return json.load(f)
    …
54 0 Open
Algorithms & data structures easy

Depth First Search Traversal Order in Python

Recursive depth-first search that returns the visit order of nodes in an adjacency list graph starting from a given node.

dfs graph traversal
Python
def dfs_order(adj, start):
    visited = set()
    order = []

    def dfs(node):
        visited.add(node)
        order.append(node)
        for neighbor in adj.get(node, []):
            if neighbor not in visited:
                dfs(neighbor)

    dfs(start)
    return order


if __name__ == "__main__":
    # Dem…
15 0 Open
Algorithms & data structures easy

Find All Indices of a Target Value in a Python List

Returns a list of all indices where a given target value appears in a Python list using a list comprehension with enumerate.

list index enumerate
Python
def find_all_indices(arr, target):
    return [i for i, value in enumerate(arr) if value == target]

if __name__ == "__main__":
    sample_list = [4, 2, 7, 2, 9, 2, 1, 2]
    target = 2
    result = find_all_indices(sample_list, target)
    print(result)
13 0 Open
Algorithms & data structures easy

Find the First Index Where a Condition Is True in Python

Search any iterable for the first element matching a predicate and return its index, or -1 if none match.

search enumerate index
Python
def first_true_index(items, condition):
    """Return the first index where condition(item) is True, or -1 if none match."""
    for i, item in enumerate(items):
        if condition(item):
            return i
    return -1


if __name__ == "__main__":
    numbers = [1, 3, 5, 8, 10, 12]
    # Find first number greate…
12 0 Open
Algorithms & data structures easy

Find the Last Index Where a Condition Is True in Python

This code scans a sequence from the end and returns the index of the last element that satisfies a given condition, or -1 if none do.

search list reverse
Python
def last_index_where(sequence, condition):
    """Return the index of the last element in sequence that satisfies condition."""
    for i in range(len(sequence) - 1, -1, -1):
        if condition(sequence[i]):
            return i
    return -1

if __name__ == "__main__":
    numbers = [1, 4, 7, 2, 9, 5, 8, 3]
    is_…
12 0 Open
Algorithms & data structures easy

How to Find the Nearest Value to a Target in a Sorted List in Python

Use bisect to binary-search a sorted list and return the element closest to a target value.

bisect binary-search sorted-list
Python
import bisect

def nearest_value(sorted_list, target):
    if not sorted_list:
        return None
    pos = bisect.bisect_left(sorted_list, target)
    if pos == 0:
        return sorted_list[0]
    if pos == len(sorted_list):
        return sorted_list[-1]
    before = sorted_list[pos - 1]
    after = sorted_list[po…
15 0 Open
Algorithms & data structures easy

How to Get the Breadth-First Traversal Order of a Graph in Python

Performs a breadth-first search on an adjacency list and returns the order nodes are visited, using a deque for efficient queue operations.

graph bfs queue
Python
from collections import deque

def bfs_order(adjacency, start=0):
    """Return the order nodes are visited in a breadth-first traversal."""
    visited = set()
    order = []
    queue = deque([start])
    visited.add(start)

    while queue:
        node = queue.popleft()
        order.append(node)

        for neig…
14 0 Open
AI & LLM integration patterns easy

How to Build an In-Memory Vector Store in Python

Build a lightweight in-memory vector store using a Python dict and cosine similarity for fast nearest-neighbor searches.

vector-store cosine-similarity embeddings
Python
import math
from typing import Dict, List, Optional


class InMemoryVectorStore:
    def __init__(self) -> None:
        self.vectors: Dict[str, List[float]] = {}
        self.index: Dict[str, List[str]] = {}  # query -> list of ids sorted by similarity

    def add(self, vector_id: str, vector: List[float]) -> None:
…
12 0 Open
Automation & scripting easy

How to Recover Deleted .txt Files from a Backup in Python

A Python function that searches a backup directory recursively and copies all .txt files to a destination folder, printing each recovered file name and a total count.

backup recovery file-operations
Python
import os
import shutil
from pathlib import Path

def recover_deleted_txt_files(source_backup_dir: str, destination_dir: str) -> None:
    """Recover .txt files from backup directory."""
    backup_path = Path(source_backup_dir)
    dest_path = Path(destination_dir)
    dest_path.mkdir(parents=True, exist_ok=True)

  …
39 0 Open
Git + Python easy

Bisect Good Bad Automation Script in Python

This Python script implements a binary search to find the first bad version in a list, simulating an automation script for git bisect.

bisect binary-search git
Python
import bisect

def find_first_bad(versions):
    """Given a list of version objects with .is_bad(), find first bad version."""
    lo, hi = 0, len(versions)
    while lo < hi:
        mid = (lo + hi) // 2
        if versions[mid].is_bad():
            hi = mid
        else:
            lo = mid + 1
    return lo

clas…
17 0 Open
Testing & modern typing easy

How to Test Hypotheses with Property-Based Check in Python

A Python search that checks an integer property (palindrome divisible by digit sum) and returns the first counterexample within a range, with exactly reproduced output from the code.

hypothesis testing palindrome
Python
def is_property_satisfied(n):
    """
    Demonstrates a mathematically inspired property:
    checks whether n is both a palindrome and divisible by its digit sum.
    """
    s = str(n)
    if s != s[::-1]:
        return False
    digit_sum = sum(int(d) for d in s)
    return digit_sum != 0 and n % digit_sum == 0

…
10 0 Open
ML engineering pipelines easy

Grid Search Hyperparameters in Python

Perform exhaustive grid search over hyperparameter combinations using itertools.product and a scoring function.

grid-search hyperparameters itertools
Python
import itertools

def grid_search(param_grid, score_fn):
    """Perform exhaustive grid search over hyperparameter combinations."""
    keys = param_grid.keys()
    names = list(keys)
    values = [param_grid[name] for name in names]
    results = []

    for combination in itertools.product(*values):
        params =…
14 0 Open
ML engineering pipelines easy

How to Do Random Search for Hyperparameter Tuning in Python

A mock random search that samples hyperparameter combinations from a grid and ranks them by a dummy score, with a reproducible seed.

hyperparameter random-search ml
Python
import random

# Mock random search over a small hyperparameter grid
param_grid = {
    "learning_rate": [0.001, 0.01, 0.1],
    "batch_size": [16, 32, 64],
    "num_layers": [1, 2, 3]
}

def random_search(grid, n_iter=5, seed=42):
    """Perform random search over a hyperparameter grid."""
    random.seed(seed)
    k…
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.