Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Memory Map Large Files Read-Only in Python
This code demonstrates reading only the tail of a large file using a read-only memory map (mmap) to avoid loading the entire file into memory.
import mmap
import os
def read_tail_with_mmap(filepath, bytes_from_end=64):
"""Read the last bytes of a large file using a read-only mmap."""
file_size = os.path.getsize(filepath)
start = max(0, file_size - bytes_from_end)
with open(filepath, "rb") as f:
with mmap.mmap(f.fileno(), length=0, a…
How to Use MappingProxyType to Create Immutable Dict Views in Python
Create a read-only, immutable view of a dictionary using MappingProxyType from the types module, while the original dict stays mutable.
from types import MappingProxyType
config = {"debug": True, "port": 8080}
# Create an immutable read-only view of the dict
read_only_config = MappingProxyType(config)
print(f"Read-only value: {read_only_config['debug']}")
print(f"Dict is mapping: {isinstance(read_only_config, dict)}")
# Original dict can still be …
How to Use Broadcast Variables as Read-Only in PySpark (Mock Example)
Share a lookup dict across Spark executors with a broadcast variable and verify its read-only behavior in a local mock.
from pyspark import SparkContext, SparkConf
def main():
conf = SparkConf().setAppName("BroadcastMock").setMaster("local[2]")
sc = SparkContext(conf=conf)
lookup = {"a": 1, "b": 2, "c": 3}
broadcast_lookup = sc.broadcast(lookup)
data = ["a", "b", "c", "a", "unknown"]
rdd = sc.parallel…
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.