Reference library

Python Code Samples

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

276 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

Extract Email-Like Tokens from Text in Python

Uses a regular expression to find all email-like tokens in a string, returning them as a list with re.findall.

regex email findall
Python
import re

def extract_email_like_tokens(text):
    pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b'
    return re.findall(pattern, text)

if __name__ == "__main__":
    sample_text = (
        "Contact us at support@example.com or sales@company.co.uk. "
        "Invalid: hello@world, user@.com, test@do…
17 0 Open
Strings & text easy

How to Build a Basic Text Processor in Python

Split text into sentences, count words, find the longest word, and convert text to uppercase — all with pure Python string methods.

string text-processing split
Python
text = """The quick brown fox jumps over the lazy dog.
Python is a powerful programming language.
Keep practicing every single day!"""

sentences = text.split(". ")
word_count = 0
longest_word = ""

for sentence in sentences:
    words = sentence.split()
    word_count += len(words)
    for word in words:
        clea…
14 0 Open
Strings & text easy

How to Check Palindrome in Python (Ignore Case and Spaces)

Check whether a string is a palindrome while ignoring case, spaces, and all non-alphanumeric characters using Python's filter and string reversal.

palindrome string case-insensitive
Python
def is_palindrome(text: str) -> bool:
    cleaned = ''.join(char.lower() for char in text if char.isalnum())
    return cleaned == cleaned[::-1]

if __name__ == "__main__":
    test_cases = [
        "A man, a plan, a canal: Panama",
        "race a car",
        "Was it a car or a cat I saw?",
        "hello",
      …
14 0 Open
Strings & text easy

How to Detect PII in Documents Using Python

Use regex patterns to automatically detect emails, phone numbers, SSNs, and credit card numbers in text documents.

pii regex data-privacy
Python
import re
from typing import List, Dict

def detect_pii(text: str) -> Dict[str, List[str]]:
    patterns = {
        "email": r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}",
        "phone": r"\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}",
        "ssn": r"\b\d{3}-\d{2}-\d{4}\b",
        "credit_card": r"\b\d{4}[- ]?\d{4}[-…
51 0 Open
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 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
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 Sort Text Alphabetically in Python

Sort words or lines alphabetically with case-insensitive ordering while preserving original casing.

sorting text-processing strings
Python
def sort_words(text):
    """Sort words alphabetically (case-insensitive), preserving case."""
    words = text.split()
    return sorted(words, key=str.lower)


def sort_lines(text):
    """Sort lines alphabetically (case-insensitive), preserving case."""
    lines = [line for line in text.splitlines() if line.strip(…
11 0 Open
Strings & text easy

How to Sort Text in Python with a Simple Helper Function

A compact helper function that sorts a list of strings or splits a string into words and sorts them alphabetically, with optional reverse ordering.

sorting strings text-processing
Python
def sort_text(data, reverse=False):
    """
    Sort a list of strings (or a single string split into words) alphabetically.
    """
    if isinstance(data, str):
        words = data.split()
    else:
        words = [str(item) for item in data]
    return sorted(words, reverse=reverse)


if __name__ == "__main__":
 …
11 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
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

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

Find Local Minima (Valleys) in a Numeric List in Python

This code finds indices of all local minima (valleys) in a numeric list, including edge cases, using a simple loop that compares each element with its neighbors.

local minima valleys list
Python
def find_local_minima(numbers):
    """Find indices of local minima (valleys) in a numeric list.
    
    A value is a local minimum if it's less than or equal to its neighbors.
    Edge elements are considered minima if they're less than or equal to their single neighbor.
    """
    if not numbers:
        return []…
14 0 Open
Lists & loops easy

Find Maximum Value in a List of Numbers in Python

Iterate through a list with a for loop to manually find and return the maximum numeric value.

max list loop
Python
def find_max(numbers):
    """Return the maximum value in a list of numbers."""
    if not numbers:
        return None
    max_value = numbers[0]
    for num in numbers[1:]:
        if num > max_value:
            max_value = num
    return max_value

if __name__ == "__main__":
    sample_list = [3, 7, 2, 15, 9, 11]
…
15 0 Open
Lists & loops easy

How to Build a Running Maximum List in Python

Compute a list where each element is the maximum of all numbers seen so far from an input list.

running-max iteration lists
Python
def running_maximum(numbers):
    result = []
    current_max = float('-inf')
    for num in numbers:
        if num > current_max:
            current_max = num
        result.append(current_max)
    return result

if __name__ == "__main__":
    numbers = [3, 1, 4, 1, 5, 9, 2, 6]
    max_list = running_maximum(number…
15 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 Calculate the Sum of List Elements in Python

Iterates over a list with a for loop, accumulates each number into a total variable, and returns the sum of all elements.

sum list loop
Python
def sum_list_elements(numbers):
    """Return the sum of all elements in a list."""
    total = 0
    for num in numbers:
        total += num
    return total

if __name__ == "__main__":
    sample_list = [1, 2, 3, 4, 5]
    result = sum_list_elements(sample_list)
    print(f"The sum of {sample_list} is {result}")
13 0 Open
Lists & loops easy

How to Check if a List is Sorted in Descending Order in Python

This code defines a function that returns True if a given list is sorted in descending order, using a generator expression with all() to compare each adjacent pair.

sorted descending list
Python
def is_descending(lst):
    """Return True if list is sorted in descending order."""
    return all(lst[i] >= lst[i + 1] for i in range(len(lst) - 1))


if __name__ == "__main__":
    test_cases = [
        [5, 4, 3, 2, 1],
        [3, 3, 2, 1],
        [1, 2, 3],
        [10, 8, 9],
        []
    ]

    for case in …
12 0 Open
Lists & loops easy

How to Convert Data Types in Python Lists

Convert a mixed list of values to integers, floats, or strings based on their content, with graceful fallback for unparseable strings.

type-conversion loops lists
Python
def convert_data(data):
    """Convert a mixed list of values to strings, ints, and floats."""
    result = []
    for item in data:
        if isinstance(item, (int, float)):
            result.append(str(item))
        elif isinstance(item, str):
            try:
                if '.' in item:
                    r…
13 0 Open
Lists & loops easy

How to Find Local Maxima in a Python List

Return the indices of all local maxima in a numeric list, where a peak is an element greater than both its immediate neighbors.

local-maxima peaks list
Python
def find_peaks(numbers):
    """
    Return the indices of local maxima in a numeric list.
    A local maximum is an element greater than both its neighbors.
    """
    if len(numbers) < 3:
        return []
    
    peaks = []
    for i in range(1, len(numbers) - 1):
        if numbers[i] > numbers[i - 1] and number…
15 0 Open
Lists & loops easy

How to Find the Third Smallest Element in a Python List

Find the third smallest distinct value in a Python list by sorting unique elements and returning the third index.

sorting lists unique
Python
def find_third_smallest(numbers):
    if len(numbers) < 3:
        return None
    
    unique_sorted = sorted(set(numbers))
    
    if len(unique_sorted) < 3:
        return None
    
    return unique_sorted[2]


if __name__ == "__main__":
    sample = [5, 2, 8, 2, 9, 1, 7, 3]
    result = find_third_smallest(sampl…
15 0 Open
Lists & loops easy

How to Sort a List of Dictionaries by a Key in Python

Sort a list of dictionaries by a specified key field, optionally in descending order, using Python's built-in sorted() function.

sort dictionaries list
Python
def sort_dicts_by_key(data, key, reverse=False):
    return sorted(data, key=lambda item: item.get(key), reverse=reverse)


if __name__ == "__main__":
    people = [
        {"name": "Alice", "age": 30},
        {"name": "Bob", "age": 25},
        {"name": "Charlie", "age": 35},
    ]

    sorted_by_age = sort_dicts_b…
14 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.