Reference library

Python Code Samples

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

7 matches
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
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

How to Split a Large File into Fixed-Size Parts in Python

Splits any binary or text file into multiple part files of a fixed byte size using Python's standard library.

file-splitting binary chunking
Python
import os
import math

def split_file(filepath, chunk_size_bytes):
    """Split a file into parts of fixed size (bytes). Creates part files in same directory."""
    filepath = os.path.abspath(filepath)
    basename = os.path.basename(filepath)
    file_size = os.path.getsize(filepath)
    num_parts = math.ceil(file_s…
14 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 Split Data into Chunks and Use Generators in Python

Split a list into fixed-size chunks with a list comprehension and square even numbers lazily with a generator expression.

comprehensions generators chunking
Python
def split_numbers(data, chunk_size):
    return [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)]


def square_even_numbers(numbers):
    return (n ** 2 for n in numbers if n % 2 == 0)


if __name__ == "__main__":
    sample_data = list(range(1, 21))
    chunks = split_numbers(sample_data, 5)
    print…
15 0 Open
AI & LLM integration patterns easy

How to Chunk a Long Document for RAG Retrieval in Python

Split text into overlapping chunks at sentence boundaries using a custom Python function suitable for RAG retrieval pipelines.

rag text-chunking nlp
Python
import re
from pathlib import Path

def chunk_document(text, chunk_size=500, overlap=100):
    """Split text into overlapping chunks suitable for RAG retrieval."""
    # Normalize whitespace
    text = re.sub(r'\s+', ' ', text).strip()
    
    chunks = []
    start = 0
    while start < len(text):
        end = min(s…
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.