Reference library

Python Code Samples

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

306 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

Count Characters, Words, and Lines in Python Text

Counts characters, words, lines, and the most common words in a given string using Python's standard library.

text-analysis counter strings
Python
from collections import Counter


def count_data(text):
    """Count characters, words, lines, and most common words in text."""
    char_count = len(text)
    word_count = len(text.split())
    line_count = text.count("\n") + 1
    word_freq = Counter(text.lower().split())
    most_common = word_freq.most_common(3)

…
17 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 Pad a String with Zeros in Python

Pad a string to a fixed width by left-filling it with zeros using the built-in str.zfill method.

strings padding zfill
Python
def pad_zeros(s, width):
    return s.zfill(width)

if __name__ == "__main__":
    print(repr(pad_zeros("42", 6)))
    print(repr(pad_zeros("-7", 5)))
    print(repr(pad_zeros("hello", 10)))
    print(repr(pad_zeros("123", 3)))
16 0 Open
Strings & text easy

Repeat a string n times with a separator in Python

Repeats a string a given number of times, joining the repetitions with an optional separator, with a guard for non-positive counts.

strings repeat join
Python
def repeat_string_with_separator(s, n, sep=''):
    """
    Repeats a string n times, joining with a separator.
    
    Args:
        s (str): The string to repeat.
        n (int): Number of repetitions.
        sep (str): Separator between repetitions (default: '').
    
    Returns:
        str: The repeated strin…
12 0 Open
Strings & text easy

Reverse Words in a Sentence While Keeping Punctuation in Python

Reverses the order of words in a sentence while leaving punctuation and spaces in their original positions using Python's re module.

strings punctuation regex
Python
def reverse_words_preserving_punctuation(sentence: str) -> str:
    import re
    # Split into words and punctuation tokens
    tokens = re.findall(r'\w+|[^\w\s]|\s+', sentence)
    words = [t for t in tokens if re.fullmatch(r'\w+', t)]
    words.reverse()
    result_parts = []
    word_index = 0
    for token in toke…
13 0 Open
Lists & loops easy

Find Most Active Contributors in a Repository with Python

Filter recent commits by date and count the most active contributors using Counter and datetime.

collections datetime counter
Python
from collections import Counter
from datetime import datetime, timedelta

# Simulated commit data
commits = [
    {"author": "Alice", "timestamp": datetime.now() - timedelta(days=1)},
    {"author": "Bob", "timestamp": datetime.now() - timedelta(days=2)},
    {"author": "Alice", "timestamp": datetime.now() - timedelta…
45 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 Parse Bullet Points in Python

Extract bullet point items from raw text by splitting lines and filtering those that start with '- ' or '* '.

text parsing bullet points loops
Python
def parse_bullet_points(text):
    """Extract bullet point items from raw text."""
    lines = text.splitlines()
    items = []
    
    for line in lines:
        stripped = line.strip()
        if stripped.startswith("- ") or stripped.startswith("* "):
            item = stripped[2:]
            if item:
           …
13 0 Open
Lists & loops easy

How to Rotate a List in Python

Rotate a list to the right by k positions using Python's list slicing and modulo arithmetic.

list rotation slicing
Python
def rotate_list_right(lst, k):
    if not lst:
        return lst
    k = k % len(lst)
    return lst[-k:] + lst[:-k] if k != 0 else lst


if __name__ == "__main__":
    sample = [1, 2, 3, 4, 5, 6, 7]
    for k in [0, 1, 3, 8, 20]:
        print(f"k={k}: {rotate_list_right(sample, k)}")
15 0 Open
Lists & loops easy

How to Transpose a Matrix in Python (List of Lists)

Swap rows and columns of a 2D list using nested loops to produce a transposed matrix.

matrix transpose 2d-list
Python
def transpose(matrix):
    # Number of rows and columns in the original matrix
    rows = len(matrix)
    cols = len(matrix[0]) if rows > 0 else 0
    
    # Create a new matrix with dimensions swapped
    result = []
    for j in range(cols):
        new_row = []
        for i in range(rows):
            new_row.appe…
13 0 Open
Lists & loops easy

Rotate List Left by k Positions in Python

Rotates a list left by k positions using slicing and modulo arithmetic to handle large k safely.

list rotation slicing
Python
def rotate_left(lst, k):
    if not lst:
        return []
    k = k % len(lst)
    return lst[k:] + lst[:k]

if __name__ == "__main__":
    my_list = [1, 2, 3, 4, 5]
    k = 2
    result = rotate_left(my_list, k)
    print(f"Original: {my_list}")
    print(f"After rotating left by {k}: {result}")
13 0 Open
Functions & basics easy

Build a Context Manager in Python with contextlib.contextmanager

Create a reusable context manager that safely opens and closes files using the contextlib contextmanager decorator.

context manager contextlib file handling
Python
from contextlib import contextmanager

@contextmanager
def managed_file(filename, mode='r'):
    """Context manager that opens and closes a file safely."""
    file = open(filename, mode)
    yield file
    file.close()

if __name__ == "__main__":
    # Write a sample file
    with managed_file("sample.txt", "w") as f…
15 0 Open
Functions & basics easy

Calculate Time Difference Across Time Zones in Python

Compute the current time difference in hours between two time zones given their UTC offsets using Python's datetime and timezone modules.

datetime timezone timedelta
Python
from datetime import datetime, timezone, timedelta

def time_difference(from_tz_offset, to_tz_offset):
    """
    Calculate time difference in hours between two time zones given their offsets from UTC.
    Offsets are in hours (e.g., -5 for EST, +5.5 for IST).
    """
    tz1 = timezone(timedelta(hours=from_tz_offset…
46 0 Open
Functions & basics easy

How to Build Partial Functions with functools.partial in Python

Create reusable partial functions that pre-fill arguments using functools.partial, like making square and cube functions from a general power function.

functools partial higher-order-functions
Python
```python
from functools import partial

def power(base, exponent):
    """Calculate base raised to the exponent power."""
    return base ** exponent

# Create partial functions for common powers
square = partial(power, exponent=2)
cube = partial(power, exponent=3)

if __name__ == "__main__":
    squares = [square(x)…
12 0 Open
Functions & basics easy

How to Compose Two Functions into a Single Callable in Python

Combine two Python functions into a single callable using a compose helper, then apply the chained call.

functions composition lambda
Python
def add_one(x):
    return x + 1

def double(x):
    return x * 2

def compose(f, g):
    return lambda x: f(g(x))

add_then_double = compose(double, add_one)
double_then_add = compose(add_one, double)

result1 = add_then_double(5)
result2 = double_then_add(5)

print(f"add_one then double(5) = {result1}")
print(f"doub…
12 0 Open
Functions & basics medium

How to Create a Counter Closure in Python

Build a closure in Python that remembers and increments a counter across calls without using global variables.

closures nonlocal state
Python
def create_counter(start=0):
    count = start
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

if __name__ == "__main__":
    counter = create_counter(10)
    print(counter())
    print(counter())
    print(counter())
12 0 Open
Functions & basics easy

How to Create a Higher-Order Function in Python (Apply Twice)

This code defines a higher-order function that takes another function and a value, then applies the function twice to the value and returns the result.

higher-order functions composition
Python
def apply_twice(func, value):
    return func(func(value))

def add_ten(x):
    return x + 10

def square(x):
    return x ** 2

if __name__ == "__main__":
    print(apply_twice(add_ten, 5))
    print(apply_twice(square, 3))
12 0 Open
Functions & basics easy

How to Parse Command Line Arguments in Python with argparse

Build a CLI that accepts positional integers, an optional --sum flag, and a --verbose switch, all with Python's standard argparse library.

argparse cli command line
Python
import argparse

def main():
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('numbers', metavar='N', type=int, nargs='+',
                        help='an integer for the accumulator')
    parser.add_argument('--sum', dest='accumulate', action='store_const',
         …
11 0 Open
Functions & basics medium

How to Parse Function Signatures in Python with inspect

Extract a function's parameter names, kinds, defaults, annotations, and return type using Python's built-in inspect module.

inspect function signature introspection
Python
import inspect

def example_function(a: int, b: str = "default", *args, c: float = 1.5, **kwargs) -> bool:
    """An example function with various parameter types."""
    return True

def parse_signature(func):
    """Parse a function's signature using the inspect module."""
    sig = inspect.signature(func)
    param…
14 0 Open
Functions & basics easy

How to Read Environment Variables in Python with Default Values

Retrieve an environment variable safely using os.getenv() with a fallback default when the variable is missing.

environment-variables os configuration
Python
import os

database_url = os.getenv("DATABASE_URL", "postgresql://localhost:5432/mydb")
print(f"Database URL: {database_url}")
10 0 Open
Functions & basics easy

How to Use *args and **kwargs in Python Functions

Implement a variadic function that accepts arbitrary positional and keyword arguments using *args and **kwargs.

args kwargs variadic
Python
def display_info(title, *args, **kwargs):
    """Display positional and keyword arguments received."""
    print(f"Title: {title}")
    print(f"Additional positional args ({len(args)}):")
    for i, arg in enumerate(args, 1):
        print(f"  {i}. {arg}")
    print(f"Keyword args ({len(kwargs)}):")
    for key, value…
14 0 Open
Functions & basics easy

How to Use Default Parameters in Python Functions

Define a Python function with default parameters and call it using positional and keyword arguments.

functions default-parameters arguments
Python
def greet(name, greeting="Hello", punctuation="!"):
    """Concatenate a greeting message with default parameters."""
    return f"{greeting}, {name}{punctuation}"

if __name__ == "__main__":
    print(greet("Alice"))                 # Uses both defaults
    print(greet("Bob", "Hi"))             # Uses default punctua…
13 0 Open
Functions & basics easy

How to Use Keyword-Only Arguments in Python Functions

Define Python functions with keyword-only arguments using the * separator to enforce clarity and prevent positional misuse.

functions keyword-arguments function-signature
Python
def greet(name, *, greeting="Hello", punctuation="!"):
    """Greet someone with a customizable message using keyword-only arguments."""
    message = f"{greeting}, {name}{punctuation}"
    return message

if __name__ == "__main__":
    # Basic call with only the positional argument
    print(greet("Alice"))

    # Al…
15 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.