Sponsored Reserved space — layout preview until AdSense is connected

Reference library

Python code samples

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

5 matches
Sponsored Reserved space — layout preview until AdSense is connected
Lists & loops medium

List comprehension filter

Build a new list in one line by filtering and transforming items.

lists comprehension filter
Python
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)
4 0 Open
Functions & basics medium

Return multiple values

Return a tuple of results and unpack them at the call site.

functions return tuple
Python
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}")
4 0 Open
Files & data medium

Read a text file with pathlib

Open and read UTF-8 text using pathlib.Path — modern and portable.

files pathlib io
Python
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.")
2 0 Open
Files & data medium

Parse JSON safely

Load JSON from a string and handle decode errors without crashing.

json parsing stdlib
Python
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}")
3 0 Open
Errors & debugging medium

Raise a clear custom error

Validate input early and raise ValueError with a helpful message.

errors raise validation
Python
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)
3 1 Open

Browse by section

Each section groups closely related Python snippets.