Reference library
Python code samples
Medium snippets you can copy, study, and run in the browser editor.
List comprehension filter
Build a new list in one line by filtering and transforming items.
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
doubled_evens = [n * 2 for n in numbers if n % 2 == 0]
print(doubled_evens)
names = ["ada", "linus", "guido"]
title_case = [name.title() for name in names if name]
print(title_case)
Return multiple values
Return a tuple of results and unpack them at the call site.
def min_max(values):
if not values:
return None, None
return min(values), max(values)
data = [3, 9, 1, 7]
lo, hi = min_max(data)
print(f"range: {lo} .. {hi}")
Read a text file with pathlib
Open and read UTF-8 text using pathlib.Path — modern and portable.
from pathlib import Path
path = Path("notes.txt")
if path.is_file():
text = path.read_text(encoding="utf-8")
print(text[:200])
else:
print("File not found — create notes.txt to try this sample.")
Parse JSON safely
Load JSON from a string and handle decode errors without crashing.
import json
payload = '{"name": "Ada", "skills": ["Python", "math"]}'
try:
data = json.loads(payload)
print(data["name"])
print(", ".join(data["skills"]))
except json.JSONDecodeError as exc:
print(f"Invalid JSON: {exc}")
Raise a clear custom error
Validate input early and raise ValueError with a helpful message.
def positive_only(n):
"""Return n if it is strictly positive."""
if n <= 0:
raise ValueError(f"Expected a positive number, got {n}")
return n
print(positive_only(5))
try:
positive_only(-1)
except ValueError as exc:
print(exc)
Browse by section
Each section groups closely related Python snippets.