Reference library

Python Code Samples

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

51 matches
Lists & loops easy

How to Compute Sliding Window Sum of Size k in Python

Compute the sum of every contiguous subarray of a fixed size k using an efficient O(n) sliding window technique.

sliding-window list sum
Python
def sliding_window_sum(nums, k):
    """Return a list of sums for each contiguous subarray of size k."""
    if not nums or k <= 0 or k > len(nums):
        return []
    
    result = []
    window_sum = sum(nums[:k])
    result.append(window_sum)
    
    for i in range(k, len(nums)):
        window_sum += nums[i] -…
12 0 Open
Lists & loops easy

How to Compute a Moving Average in Python

This code computes the moving average over a numeric list using an efficient sliding window sum, avoiding recomputation of each window.

moving-average sliding-window lists
Python
def moving_average(data, window_size):
    """
    Compute the moving average over a numeric list.
    
    Args:
        data: List of numeric values
        window_size: Size of the sliding window (positive integer)
    
    Returns:
        List of moving averages, each representing the mean of a window
    """
   …
14 0 Open
Lists & loops easy

How to Pad a List to Length n in Python with a Fill Value

Create a reusable function that pads a Python list to a specified length n by appending a fill value, or truncates it when the list is already longer than n.

lists padding slicing
Python
def pad_list(lst, n, fill_value=None):
    """
    Pad a list to length n using fill_value for missing elements.
    If the list is longer than n, it is truncated to length n.
    """
    if n <= len(lst):
        return lst[:n]
    return lst + [fill_value] * (n - len(lst))


if __name__ == "__main__":
    # Examples…
14 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 Split a List at the First Occurrence of a Value in Python

This function splits a list into two parts at the first occurrence of a given value, returning the left and right portions.

list slicing split
Python
def split_at_first(lst, value):
    try:
        idx = lst.index(value)
        return lst[:idx], lst[idx:]
    except ValueError:
        return lst, []

if __name__ == "__main__":
    sample = [1, 2, 3, 4, 3, 5]
    value = 3
    left, right = split_at_first(sample, value)
    print("Left:", left)
    print("Right:"…
13 0 Open
Lists & loops easy

How to Split a List into Chunks in Python

Split a list into fixed-size sublists using a simple list comprehension with slicing.

list slicing chunking
Python
def chunk_list(lst, size):
    """Split a list into sublists of given size."""
    return [lst[i:i + size] for i in range(0, len(lst), size)]


if __name__ == "__main__":
    sample = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    print(chunk_list(sample, 3))
13 0 Open
Lists & loops easy

How to Truncate a List to Max Length in Python (Keep Head)

This code returns a new list containing only the first max_length items from the original list, using Python's slice syntax.

list slicing truncate
Python
from typing import List

def truncate_head(lst: List[object], max_length: int) -> List[object]:
    """Return a new list with at most max_length items from the head."""
    if max_length < 0:
        raise ValueError("max_length must be non-negative")
    return lst[:max_length]

if __name__ == "__main__":
    # Examp…
14 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
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

How to Group a List into Chunks in Python

Split a list into smaller groups of a fixed size using a reusable function with a default parameter.

list slicing functions
Python
def make_groups(numbers, group_size=2):
    """Splits a list into smaller groups of a given size."""
    groups = []
    for i in range(0, len(numbers), group_size):
        groups.append(numbers[i:i + group_size])
    return groups


if __name__ == "__main__":
    data = [1, 2, 3, 4, 5, 6, 7]

    print("Default size…
15 0 Open
Files & data easy

Parse Fixed Width Data File by Column Slices in Python

Extract fields from fixed-width text by slicing each line at defined column offsets, with a dictionary describing the boundaries.

fixed-width string-slicing parsing
Python
from pathlib import Path


def parse_fixed_width(data: str, slices: dict[str, tuple[int, int]]) -> list[dict[str, str]]:
    lines = data.strip().splitlines()
    records = []
    for line in lines:
        record = {}
        for name, (start, end) in slices.items():
            record[name] = line[start:end].strip()…
13 0 Open
OOP & classes medium

How to Create a Data Splitter Class in Python

This code defines a DataSplitter class that splits data by index, into chunks, or by a predicate, demonstrating OOP principles in Python.

class data-splitting slicing
Python
class DataSplitter:
    def __init__(self, data):
        self.data = list(data)
    
    def split_by_index(self, index):
        return self.data[:index], self.data[index:]
    
    def split_into_chunks(self, chunk_size):
        return [self.data[i:i + chunk_size] for i in range(0, len(self.data), chunk_size)]
   …
13 0 Open
Algorithms & data structures easy

How to Apply a Function to Sliding Window Slices in Python

This Python code applies a given function to every contiguous window of a specified size in a list, returning a list of results.

sliding-window list-comprehension algorithms
Python
def apply_to_sliding_windows(data, window_size, func):
    return [func(data[i:i + window_size]) for i in range(len(data) - window_size + 1)]

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5, 6]
    window_size = 3
    results = apply_to_sliding_windows(numbers, window_size, sum)
    print(results)
    results…
16 0 Open
Algorithms & data structures easy

How to Implement a Moving Average from a Data Stream in Python

Implement a MovingAverage class using a deque and running sum to compute the average of the last k values from a continuous data stream.

deque sliding-window streaming
Python
from collections import deque

class MovingAverage:
    def __init__(self, size):
        self.size = size
        self.queue = deque()
        self.window_sum = 0

    def next(self, val):
        self.queue.append(val)
        self.window_sum += val

        if len(self.queue) > self.size:
            self.window_su…
12 0 Open
Algorithms & data structures easy

How to Implement a Recent Counter with a Deque in Python

Implements a RecentCounter class that uses a deque to count ping requests within the last 3000 milliseconds.

deque recents sliding-window
Python
from collections import deque
import time


class RecentCounter:
    def __init__(self):
        self.hits = deque()

    def ping(self, t: int) -> int:
        self.hits.append(t)
        while self.hits and self.hits[0] < t - 3000:
            self.hits.popleft()
        return len(self.hits)


if __name__ == "__mai…
11 0 Open
Algorithms & data structures easy

How to Rotate an Array by k Steps in Python

This code rotates a list to the right by k positions using modulo arithmetic to handle k larger than the list length.

array rotation algorithms
Python
def rotate_array(nums, k):
    if not nums:
        return []
    n = len(nums)
    k = k % n
    return nums[-k:] + nums[:-k] if k else nums[:]

if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5, 6]
    k = 2
    result = rotate_array(arr, k)
    print(f"Original: {arr}")
    print(f"Rotated by {k}: {result}")
13 0 Open
Algorithms & data structures easy

How to partition a list into n nearly equal parts in Python

Divide a list into n contiguous chunks of nearly equal size using an average-length calculation that distributes the remainder evenly.

partitioning chunks slicing
Python
def partition(lst, n):
    """Partition a list into n nearly equal contiguous parts."""
    if n <= 0:
        raise ValueError("n must be positive")
    if not lst:
        return [[] for _ in range(n)]
    
    parts = []
    avg = len(lst) / n
    last_idx = 0.0
    
    while last_idx < len(lst):
        end_idx =…
14 0 Open
Algorithms & data structures easy

Remove item at index without pop in Python

Remove an item at a given index from a list without using pop by slicing the list around the index.

list slicing algorithms
Python
def remove_at_index(lst, index):
    """Remove item at index and return the new list."""
    if index < 0 or index >= len(lst):
        raise IndexError("Index out of range")
    return lst[:index] + lst[index + 1:]


if __name__ == "__main__":
    items = [10, 20, 30, 40, 50]
    result = remove_at_index(items, 2)
  …
12 0 Open
Algorithms & data structures easy

Reorder a List by Odd Even Indices in Python

Splits a list into two sublists based on 1-based index parity, then concatenates odd-indexed elements before even-indexed ones.

list indices reorder
Python
def reorder_by_odd_even(items):
    """Reorders a list so that elements at odd indices come first,
    followed by elements at even indices (1-based).
    
    Example: [0,1,2,3,4,5,6] -> [1,3,5,0,2,4,6]
    """
    odds = [items[i] for i in range(1, len(items), 2)]
    evens = [items[i] for i in range(0, len(items), …
18 0 Open
Comprehensions & generators easy

Batch Rows in Chunks with a Generator in Python

Group a list of row dicts into fixed-size chunks using a generator that yields one slice per call.

generators chunking database
Python
from typing import Iterator, List


def batch_rows(rows: List[dict], batch_size: int) -> Iterator[List[dict]]:
    for i in range(0, len(rows), batch_size):
        yield rows[i:i + batch_size]


if __name__ == "__main__":
    sample_rows = [
        {"id": 1, "name": "Alice"},
        {"id": 2, "name": "Bob"},
      …
14 0 Open
Comprehensions & generators easy

Chunk an Iterable into Batches with a Generator in Python

Yield fixed-size batches from any iterable lazily using itertools.islice inside a generator function.

generators iterators itertools
Python
from itertools import islice

def chunked(iterable, size):
    iterator = iter(iterable)
    while True:
        batch = list(islice(iterator, size))
        if not batch:
            break
        yield batch

if __name__ == "__main__":
    data = range(10)
    for batch in chunked(data, 3):
        print(batch)
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 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

Take n items from an infinite Python generator

Uses itertools.islice to lazily take exactly n items from an infinite generator without exhausting it.

generators itertools islice
Python
from itertools import islice

def count_up_from(start=0):
    n = start
    while True:
        yield n
        n += 1

def take_n(generator, count):
    return list(islice(generator, count))

if __name__ == "__main__":
    gen = count_up_from(10)
    result = take_n(gen, 5)
    print(result)
11 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.