Reference library

Python Code Samples

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

33 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

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

Truncate List Keeping Last N Elements in Python

Return a new list containing only the last N elements from a sequence, handling edge cases like zero or oversized counts.

list slicing sequence
Python
def truncate(seq, keep_last_n):
    """Return a new list keeping only the last n elements."""
    if keep_last_n <= 0:
        return []
    return list(seq)[-keep_last_n:]


if __name__ == "__main__":
    data = [10, 20, 30, 40, 50, 60]
    print(truncate(data, 3))
    print(truncate(data, 0))
    print(truncate(data…
11 0 Open
Functions & basics easy

Chain Generators with yield from in Python

Combine multiple generators into one seamless sequence using the `yield from` delegation syntax in Python.

generators yield delegation
Python
def numbers():
    yield 1
    yield 2
    yield 3

def letters():
    yield 'a'
    yield 'b'
    yield 'c'

def combined():
    yield from numbers()
    yield from letters()

if __name__ == "__main__":
    print(list(combined()))
14 0 Open
Functions & basics easy

How to Create Generator Functions with yield in Python

Create a memory-efficient generator function using yield to produce a Fibonacci sequence up to a limit.

generator yield fibonacci
Python
def fibonacci_sequence(limit):
    """Generate Fibonacci numbers up to a given limit."""
    a, b = 0, 1
    while a <= limit:
        yield a
        a, b = b, a + b


if __name__ == "__main__":
    fib_gen = fibonacci_sequence(100)
    
    for number in fib_gen:
        print(number, end=" ")
    print()
11 0 Open
Functions & basics easy

How to Pipe Data Through a List of Transform Functions in Python

Applies a sequence of functions to an initial value using functools.reduce, creating a reusable pipe utility.

functions functional reduce
Python
from functools import reduce

def pipe(data, *transforms):
    return reduce(lambda value, func: func(value), transforms, data)

def double(x):
    return x * 2

def add_one(x):
    return x + 1

def to_string(x):
    return f"Result: {x}"

if __name__ == "__main__":
    initial = 5
    result = pipe(initial, double, …
13 0 Open
Algorithms & data structures easy

Find Longest Consecutive Run in an Unsorted List in Python

Find the length of the longest sequence of consecutive integers in an unsorted list using a set and a linear scan.

set consecutive linear-scan
Python
def longest_run(nums):
    if not nums:
        return 0

    num_set = set(nums)
    longest = 0

    for num in num_set:
        # Only start counting from the smallest number in a sequence
        if num - 1 not in num_set:
            current = num
            length = 1
            while current + 1 in num_set:
 …
11 0 Open
Algorithms & data structures easy

Find Median of Two Sorted Arrays in Python

Merges two sorted arrays with a two-pointer walk and returns the median of the combined sorted sequence.

median two-pointer merge
Python
def median_of_two_sorted_arrays(nums1, nums2):
    merged = []
    i = j = 0
    while i < len(nums1) and j < len(nums2):
        if nums1[i] <= nums2[j]:
            merged.append(nums1[i])
            i += 1
        else:
            merged.append(nums2[j])
            j += 1
    merged.extend(nums1[i:])
    merged.…
15 0 Open
Algorithms & data structures easy

Find Missing Number in Python Sequence 1 to N

Find the missing number from a list containing numbers 1 to N using the arithmetic sum formula.

missing-number arithmetic sum
Python
def find_missing_number(nums, n):
    expected_sum = n * (n + 1) // 2
    actual_sum = sum(nums)
    return expected_sum - actual_sum


if __name__ == "__main__":
    n = 10
    numbers = [1, 2, 3, 4, 5, 6, 7, 9, 10]
    missing = find_missing_number(numbers, n)
    print(f"The missing number is: {missing}")
14 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 Generate Fibonacci Sequence in Python

Generate the first n Fibonacci numbers as a list using a simple iterative loop.

fibonacci sequences iteration
Python
def fibonacci(n):
    """Generate the first n terms of the Fibonacci sequence."""
    if n <= 0:
        return []
    seq = [0, 1]
    while len(seq) < n:
        seq.append(seq[-1] + seq[-2])
    return seq[:n]

if __name__ == "__main__":
    n = 10
    result = fibonacci(n)
    print(result)
13 0 Open
Algorithms & data structures easy

How to Generate a Geometric Progression List in Python

This Python function builds a list of n terms in a geometric progression, starting with a given first term and multiplying by a constant ratio at each step.

geometric-progression sequence algorithms
Python
def geometric_progression(first_term, ratio, count):
    """
    Generate a list of 'count' terms in a geometric progression
    starting with 'first_term' and multiplied by 'ratio' each step.
    """
    progression = []
    current = first_term
    for _ in range(count):
        progression.append(current)
        c…
13 0 Open
Algorithms & data structures easy

How to Generate an Arithmetic Progression List in Python

Generates a list of terms in an arithmetic progression using a list comprehension.

arithmetic list-comprehension sequences
Python
def generate_ap(start, difference, count):
    """Generate a list of n terms in an arithmetic progression."""
    return [start + i * difference for i in range(count)]


if __name__ == "__main__":
    ap = generate_ap(3, 5, 6)
    print(ap)
14 0 Open
Algorithms & data structures easy

How to Sample Random Items Without Replacement in Python

Select k random unique items from a sequence using random.sample for uniform, non-repeating selection.

random sampling algorithms
Python
import random

def sample_without_replacement(population, k):
    """Return k random items from population without replacement."""
    if k > len(population):
        raise ValueError("k cannot exceed population size")
    # Use random.sample for O(k) time, no mutation of the original
    return random.sample(populati…
15 0 Open
Algorithms & data structures easy

Insert an Element Every n Positions in Python

Insert a given element before or after every n-th position in a Python list, returning a new list with the placements applied.

list-manipulation insertion algorithms
Python
def insert_every_n(seq, element, n, position="after"):
    """Insert an element before or after every n-th position in a list.

    Args:
        seq: Input list
        element: Element to insert
        n: Insert every n positions (n > 0)
        position: 'before' or 'after' (default: 'after')
    Returns:
        …
13 0 Open
Comprehensions & generators easy

Generator Function to Yield an Infinite Counter in Python

This code demonstrates a generator function that yields an infinite sequence of integers starting from a given value, allowing lazy, memory-efficient iteration.

generators infinite sequences yield
Python
def infinite_counter(start=0):
    count = start
    while True:
        yield count
        count += 1

if __name__ == "__main__":
    counter = infinite_counter(5)
    for _ in range(5):
        print(next(counter))
14 0 Open
Comprehensions & generators easy

How to Build a Sliding Window Generator in Python

Create a generator that yields fixed-size overlapping slices of a sequence, useful for efficient windowed iteration.

generators sliding-window iteration
Python
def sliding_window(sequence, size):
    for i in range(len(sequence) - size + 1):
        yield sequence[i:i + size]

if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]
    n = 3
    for window in sliding_window(data, n):
        print(window)
12 0 Open
Comprehensions & generators easy

How to Create an Infinite Arithmetic Sequence Generator in Python

Build a memory-efficient generator that yields an infinite arithmetic progression and extract the first N values with list comprehension.

generators yield infinite-sequences
Python
"""Count generator infinite arithmetic progression"""


def arithmetic_counter(start=0, step=1):
    """Generate an infinite arithmetic sequence."""
    current = start
    while True:
        yield current
        current += step


if __name__ == "__main__":
    counter = arithmetic_counter(1, 3)
    result = [next(c…
14 0 Open
Comprehensions & generators easy

How to Delegate Iteration to a Subgenerator with yield from in Python

Use yield from to delegate iteration from one generator to a subgenerator, flattening nested generator output into a single sequence.

generators yield-from delegation
Python
def subgenerator():
    yield "first"
    yield "second"
    yield "third"


def delegate():
    yield "before delegation"
    yield from subgenerator()
    yield "after delegation"


if __name__ == "__main__":
    for item in delegate():
        print(item)
13 0 Open
Comprehensions & generators easy

How to Generate Fibonacci Numbers in Python Without Recursion

Build an efficient infinite Fibonacci sequence using a generator function with O(1) memory and no recursion overhead.

generators fibonacci iteration
Python
def fib(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

if __name__ == "__main__":
    count = 10
    result = list(fib(count))
    print(result)
15 0 Open
Comprehensions & generators easy

How to Generate a Collatz Sequence in Python

Generate the Collatz sequence for a given positive integer by repeatedly applying the 3n+1 rule until reaching 1.

collatz sequence loops
Python
def collatz_sequence(n):
    if n <= 0:
        raise ValueError("n must be a positive integer")
    sequence = [n]
    while n != 1:
        if n % 2 == 0:
            n = n // 2
        else:
            n = 3 * n + 1
        sequence.append(n)
    return sequence

if __name__ == "__main__":
    start = 7
    result…
14 0 Open
Comprehensions & generators easy

How to Reset Python's Random Seed for Deterministic Output

This code shows how to seed Python's random module to generate identical random sequences across runs, ensuring reproducibility.

random seeding deterministic
Python
import random

def seeded_random_sequence(seed, count=5, low=1, high=100):
    random.seed(seed)
    return [random.randint(low, high) for _ in range(count)]

if __name__ == "__main__":
    seed_value = 42
    first_run = seeded_random_sequence(seed_value)
    print("First run:", first_run)

    # Reset seed and gener…
12 0 Open
Comprehensions & generators easy

How to Slice a Generator with islice in Python

Use itertools.islice to take the first n items from any iterable without materializing the whole sequence into a list.

itertools islice generators
Python
from itertools import islice


def first_n(iterable, n):
    """Return the first n items from an iterable."""
    return list(islice(iterable, n))


if __name__ == "__main__":
    numbers = range(10, 100)  # large iterable
    result = first_n(numbers, 5)
    print(result)  # [10, 11, 12, 13, 14]
14 0 Open
Comprehensions & generators easy

How to skip items until a condition is met in Python

Use itertools.dropwhile to skip leading elements while a predicate returns true, then yield the rest of the sequence unchanged.

itertools generators dropwhile
Python
def is_negative(x):
    return x < 0

numbers = [-3, -1, 0, 5, 2, -8, 7]
result = list(itertools.dropwhile(is_negative, numbers))
print(f"Original: {numbers}")
print(f"After dropwhile: {result}")
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.