Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Split a List into Chunks in Python
Split a list into fixed-size sublists using a simple list comprehension with slicing.
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))
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.
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…
Chunk Large File Upload Simulation by Blocks in Python
A Python script reads a large binary file in fixed-size chunks and simulates a block-by-block upload with per-chunk SHA256 hashing.
import os
import hashlib
from pathlib import Path
def read_file_in_chunks(file_path, chunk_size=8196):
"""Yield chunks of a file as bytes."""
with open(file_path, 'rb') as f:
while chunk := f.read(chunk_size):
yield chunk
def simulate_chunked_upload(file_path, chunk_size=8196):
"""S…
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.
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…
Read Parquet-Like Columnar CSV Chunks in Python
A Python generator that reads a CSV file column-by-column, yielding dictionary chunks where each key points to a list of values—mirroring how Parquet stores data columnar.
```python
import csv
from pathlib import Path
from typing import Iterator, List
def read_parquet_like_columnar(csv_path: str, column_names: List[str], chunk_size: int = 2) -> Iterator[dict]:
"""Read CSV data in columnar chunks, similar to how parquet stores columns."""
csv_file = Path(csv_path)
with csv_f…
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.
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"},
…
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.
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)
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.
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…
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.
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…
Map Partition Over Chunks in Python with Multiprocessing and Mock
Process data in chunks across multiple CPU cores using multiprocessing Pool.map, and mock the chunk function to test partitioning behavior without heavy computation.
from multiprocessing import Pool
from unittest.mock import patch, Mock
def process_chunk(chunk):
return [x * x for x in chunk]
def map_partition_over_chunks(data, chunk_size, process_func=process_chunk):
chunks = [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)]
with Pool() as pool:
…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.