Skip to the content.

30 Seconds of Python: Short Python Code Snippets You Can Understand in 30 Seconds

30 Seconds of Python is a collection of 100+ short, practical Python code snippets for everyday tasks: lists, dictionaries, strings, math, decorators, generators, dates, files and asyncio. Each snippet is a small function you can read in about 30 seconds, copy into your project and trust, because every example in this README is executed as a unit test. It is for Python beginners learning idiomatic code, developers who want a quick Python cheat sheet, and anyone preparing for coding interviews.

Last reviewed: December 2026. Requires Python 3.9 or newer. Standard library only, no dependencies.

Table of contents

Why this collection

Quick start

Clone and run the tests:

git clone https://github.com/Ralpberry-Labs/30-seconds-of-python.git
cd 30-seconds-of-python
python3 -m unittest

Use a snippet from the package:

from snippets.lists import chunk
from snippets.strings import slugify

chunk(list(range(7)), 3)      # [[0, 1, 2], [3, 4, 5], [6]]
slugify("Hello, World!")      # 'hello-world'

Or simply copy the function you need. Every snippet lists its imports at the top of its module in snippets/.

Project layout:

snippets/          one module per category (lists.py, strings.py, ...)
tests/             doctest runner, edge-case tests, README sync check
docs/              generated pages with full code + examples per category
scripts/           build_readme.py regenerates README tables and docs/

How the snippets are tested

  1. Every docstring example (>>> ...) is collected by tests/test_doctests.py and run with doctest.
  2. tests/test_edge_cases.py covers inputs that would make docstrings too long: empty lists, invalid sizes, retries that give up, a concurrency cap check for gather_limited, leap-day birthdays.
  3. tests/test_readme_sync.py fails if the code in this README or in docs/ drifts from the source. Run python3 scripts/build_readme.py after editing a snippet.

Two dozen snippets people reach for most. The full list with code is in All snippets by category.

chunk

Split a list into consecutive pieces of at most size items.

def chunk(items, size):
    if size < 1:
        raise ValueError("size must be >= 1")
    return [items[i:i + size] for i in range(0, len(items), size)]
>>> chunk([1, 2, 3, 4, 5], 2)
[[1, 2], [3, 4], [5]]

unique

Remove duplicates while keeping the first-seen order.

def unique(items):
    return list(dict.fromkeys(items))
>>> unique([3, 1, 3, 2, 1])
[3, 1, 2]

group_by

Group items into a dict of lists by a key function.

def group_by(items, key):
    groups = {}
    for x in items:
        groups.setdefault(key(x), []).append(x)
    return groups
>>> group_by(["one", "two", "three"], len)
{3: ['one', 'two'], 5: ['three']}

sliding_window

Yield overlapping windows of size consecutive items.

def sliding_window(items, size):
    it = iter(items)
    window = tuple(islice(it, size))
    if len(window) == size:
        yield window
    for x in it:
        window = window[1:] + (x,)
        yield window
>>> list(sliding_window([1, 2, 3, 4], 3))
[(1, 2, 3), (2, 3, 4)]

deep_merge

Recursively merge nested dicts without mutating either input.

def deep_merge(base, override):
    out = dict(base)
    for k, v in override.items():
        if isinstance(v, dict) and isinstance(out.get(k), dict):
            out[k] = deep_merge(out[k], v)
        else:
            out[k] = v
    return out
>>> deep_merge({'db': {'host': 'x', 'port': 1}}, {'db': {'port': 2}})
{'db': {'host': 'x', 'port': 2}}

get_path

Read a nested value with a dotted path; list indexes work too.

def get_path(d, path, default=None, sep='.'):
    cur = d
    for part in path.split(sep):
        try:
            cur = cur[int(part)] if isinstance(cur, (list, tuple)) else cur[part]
        except (KeyError, IndexError, ValueError, TypeError):
            return default
    return cur
>>> cfg = {'server': {'ports': [80, 443]}}
>>> get_path(cfg, 'server.ports.1')
443
>>> get_path(cfg, 'server.host', 'localhost')
'localhost'

flatten_dict

Flatten nested dicts into one level with joined keys.

def flatten_dict(d, parent='', sep='.'):
    out = {}
    for k, v in d.items():
        key = f"{parent}{sep}{k}" if parent else str(k)
        if isinstance(v, dict) and v:
            out.update(flatten_dict(v, key, sep))
        else:
            out[key] = v
    return out
>>> flatten_dict({'a': 1, 'b': {'c': 2, 'd': {'e': 3}}})
{'a': 1, 'b.c': 2, 'b.d.e': 3}

snake_case

Convert any casing to snake_case.

def snake_case(text):
    return '_'.join(w.lower() for w in words(text))
>>> snake_case('someHTTPRequest ID')
'some_http_request_id'

slugify

URL-friendly slug: ASCII, lowercase, hyphen separated.

def slugify(text):
    ascii_text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode()
    return re.sub(r'[^a-z0-9]+', '-', ascii_text.lower()).strip('-')
>>> slugify('  Crème Brûlée: 10 Recipes! ')
'creme-brulee-10-recipes'

human_bytes

Format a byte count for people.

def human_bytes(n, binary=True):
    base = 1024 if binary else 1000
    units = ['KiB', 'MiB', 'GiB', 'TiB', 'PiB'] if binary else ['kB', 'MB', 'GB', 'TB', 'PB']
    if abs(n) < base:
        return f'{n} B'
    size = float(n)
    for unit in units:
        size /= base
        if abs(size) < base or unit == units[-1]:
            return f'{size:.1f} {unit}'
>>> human_bytes(1536)
'1.5 KiB'
>>> human_bytes(1_500_000, binary=False)
'1.5 MB'
>>> human_bytes(512)
'512 B'

clamp

Limit n to the range [low, high].

def clamp(n, low, high):
    return max(low, min(n, high))
>>> clamp(15, 0, 10), clamp(-3, 0, 10), clamp(5, 0, 10)
(10, 0, 5)

primes_up_to

Sieve of Eratosthenes: every prime <= limit.

def primes_up_to(limit):
    if limit < 2:
        return []
    sieve = bytearray([1]) * (limit + 1)
    sieve[0] = sieve[1] = 0
    for i in range(2, math.isqrt(limit) + 1):
        if sieve[i]:
            sieve[i * i::i] = bytes(len(range(i * i, limit + 1, i)))
    return [i for i, flag in enumerate(sieve) if flag]
>>> primes_up_to(30)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

retry

Decorator: retry on the given exceptions with exponential backoff.

def retry(times=3, exceptions=(Exception,), delay=0.0, backoff=2.0):
    def decorator(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            wait = delay
            for attempt in range(1, times + 1):
                try:
                    return fn(*args, **kwargs)
                except exceptions:
                    if attempt == times:
                        raise
                    if wait:
                        time.sleep(wait)
                    wait *= backoff
        return wrapper
    return decorator
>>> calls = []
>>> @retry(times=3)
... def flaky():
...     calls.append(1)
...     if len(calls) < 3:
...         raise ConnectionError('try again')
...     return 'ok'
>>> flaky(), len(calls)
('ok', 3)

once

Decorator: run fn only the first time; later calls return the first result.

def once(fn):
    result = []

    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        if not result:
            result.append(fn(*args, **kwargs))
        return result[0]
    return wrapper
>>> @once
... def init():
...     print('setting up')
...     return 42
>>> init()
setting up
42
>>> init()
42

ttl_cache

Decorator: cache results for seconds before recomputing.

def ttl_cache(seconds, clock=time.monotonic):
    def decorator(fn):
        cache = {}

        @functools.wraps(fn)
        def wrapper(*args):
            hit = cache.get(args)
            if hit and clock() - hit[0] < seconds:
                return hit[1]
            value = fn(*args)
            cache[args] = (clock(), value)
            return value
        return wrapper
    return decorator
>>> now = [0.0]
>>> @ttl_cache(10, clock=lambda: now[0])
... def stamp():
...     return now[0]
>>> stamp(); now[0] = 5; stamp(); now[0] = 11; stamp()
0.0
0.0
11

batched

Yield tuples of up to n items (itertools.batched exists in 3.12+).

def batched(iterable, n):
    if n < 1:
        raise ValueError('n must be >= 1')
    it = iter(iterable)
    while chunk := tuple(islice(it, n)):
        yield chunk
>>> list(batched('ABCDEFG', 3))
[('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)]

run_length

Run-length encode: (value, count) for each run of equal values.

def run_length(iterable):
    return [(k, sum(1 for _ in g)) for k, g in groupby(iterable)]
>>> run_length('aaabccdddd')
[('a', 3), ('b', 1), ('c', 2), ('d', 4)]

parse_iso

Parse an ISO 8601 timestamp; a trailing ‘Z’ is accepted on every Python 3.7+.

def parse_iso(text):
    if text.endswith('Z'):
        text = text[:-1] + '+00:00'
    return datetime.fromisoformat(text)
>>> parse_iso('2026-12-01T09:30:00Z')
datetime.datetime(2026, 12, 1, 9, 30, tzinfo=datetime.timezone.utc)

add_business_days

Add n weekdays (Mon-Fri) to a date. Holidays are not considered.

def add_business_days(start, n):
    step = 1 if n >= 0 else -1
    current, left = start, abs(n)
    while left:
        current += timedelta(days=step)
        if current.weekday() < 5:
            left -= 1
    return current
>>> add_business_days(date(2026, 11, 27), 1)  # Friday -> Monday
datetime.date(2026, 11, 30)

human_duration

Readable duration like ‘1h 2m 3s’.

def human_duration(seconds):
    seconds = int(seconds)
    parts = []
    for unit, size in (('d', 86400), ('h', 3600), ('m', 60), ('s', 1)):
        value, seconds = divmod(seconds, size)
        if value:
            parts.append(f'{value}{unit}')
    return ' '.join(parts) or '0s'
>>> human_duration(3723), human_duration(59), human_duration(90061)
('1h 2m 3s', '59s', '1d 1h 1m 1s')

write_atomic

Write a file so readers never see a half-written version.

def write_atomic(path, text):
    path = Path(path)
    fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f'.{path.name}.')
    try:
        with os.fdopen(fd, 'w', encoding='utf-8') as f:
            f.write(text)
            f.flush()
            os.fsync(f.fileno())
        os.replace(tmp, path)
    except BaseException:
        os.unlink(tmp)
        raise
>>> p = Path(tempfile.mkdtemp()) / 'cfg.json'
>>> write_atomic(p, '{}'); p.read_text()
'{}'

sha256_file

SHA-256 of a file, read in chunks so big files are fine.

def sha256_file(path, chunk_size=1 << 20):
    h = hashlib.sha256()
    with open(path, 'rb') as f:
        while block := f.read(chunk_size):
            h.update(block)
    return h.hexdigest()
>>> p = Path(tempfile.mkdtemp()) / 'b.bin'; _ = p.write_bytes(b'abc')
>>> sha256_file(p)[:16]
'ba7816bf8f01cfea'

gather_limited

Await coroutines with at most limit running at once; results keep order.

async def gather_limited(coros, limit):
    sem = asyncio.Semaphore(limit)

    async def run(coro):
        async with sem:
            return await coro
    return await asyncio.gather(*(run(c) for c in coros))
>>> async def double(x):
...     await asyncio.sleep(0)
...     return x * 2
>>> asyncio.run(gather_limited([double(i) for i in range(5)], limit=2))
[0, 2, 4, 6, 8]

with_timeout

Await coro but give up after seconds and return default.

async def with_timeout(coro, seconds, default=None):
    try:
        return await asyncio.wait_for(coro, seconds)
    except asyncio.TimeoutError:
        return default
>>> asyncio.run(with_timeout(asyncio.sleep(10, 'late'), 0.01, default='timeout'))
'timeout'

All snippets by category

Lists

Full code and examples: docs/lists.md

Snippet What it does
chunk Split a list into consecutive pieces of at most size items.
flatten Flatten one level of nesting.
deep_flatten Flatten lists and tuples nested to any depth (strings stay whole).
unique Remove duplicates while keeping the first-seen order.
unique_by Remove duplicates by a key function, keeping the first item per key.
duplicates Return the values that appear more than once, in first-seen order.
compact Drop falsy values (0, ‘’, None, False, empty containers).
group_by Group items into a dict of lists by a key function.
partition Split into (matching, not_matching) in a single pass.
most_frequent Return the most common value (the first one seen wins a tie).
transpose Swap rows and columns of a rectangular 2D list.
zip_fill Zip sequences of different lengths, padding the short ones.
rotate Rotate a list n places to the left (negative n rotates right).
sliding_window Yield overlapping windows of size consecutive items.
difference Items of a not in b, keeping order and duplicates of a.
intersection Items of a that are also in b, keeping the order of a.
all_equal True if every element is equal (also True for an empty list).
index_all Every index where value occurs.
sort_by_keys Sort dicts by several keys; prefix a key with ‘-‘ for descending.
first First item (optionally the first that matches predicate), else default.

Dictionaries

Full code and examples: docs/dicts.md

Snippet What it does
merge Merge dicts left to right; later keys win.
deep_merge Recursively merge nested dicts without mutating either input.
invert Swap keys and values (values must be hashable; last duplicate wins).
pick Keep only the given keys (missing keys are skipped).
omit Copy of d without the given keys.
get_path Read a nested value with a dotted path; list indexes work too.
flatten_dict Flatten nested dicts into one level with joined keys.
unflatten_dict Reverse of flatten_dict.
map_values Apply fn to every value.
filter_values Keep entries whose value matches predicate.
sort_by_value New dict ordered by value.
count_by Count items per key function result.
dict_diff Report added, removed and changed keys between two dicts.

Strings

Full code and examples: docs/strings.md

Snippet What it does
words Split text into words, understanding camelCase, snake_case and kebab-case.
snake_case Convert any casing to snake_case.
kebab_case Convert any casing to kebab-case.
camel_case Convert any casing to camelCase.
pascal_case Convert any casing to PascalCase.
slugify URL-friendly slug: ASCII, lowercase, hyphen separated.
truncate Shorten text to at most length characters including the suffix.
is_palindrome Palindrome check that ignores case, spaces and punctuation.
is_anagram True if two strings use the same letters (case and spaces ignored).
strip_accents Remove diacritics: é -> e, ñ -> n.
collapse_whitespace Turn every run of whitespace into one space and trim the ends.
count_vowels Count vowels (a, e, i, o, u), case-insensitive.
mask Hide all but the last visible characters.
wrap_lines Hard-wrap text to width columns without breaking words.
remove_prefix_suffix Strip one exact prefix and suffix if present (str.removeprefix/removesuffix).
human_bytes Format a byte count for people.

Math and numbers

Full code and examples: docs/numeric.md

Snippet What it does
clamp Limit n to the range [low, high].
in_range True if start <= n < end (with one bound, the range is 0..start).
average Arithmetic mean of the arguments.
median Middle value (the mean of the two middle values for even counts).
round_to Round to the nearest multiple of step.
percent Percentage of part in whole, rounded.
lerp Linear interpolation between a and b (t=0 gives a, t=1 gives b).
is_prime Primality test by trial division up to sqrt(n).
primes_up_to Sieve of Eratosthenes: every prime <= limit.
fibonacci First n Fibonacci numbers.
digits Decimal digits of an integer.
lcm_all Least common multiple of several integers (math.lcm, Python 3.9+).
gcd_all Greatest common divisor of several integers.
is_close Float comparison that survives rounding error.
to_base Integer to a string in base 2..36.

Functions and decorators

Full code and examples: docs/functions.md

Snippet What it does
compose Right-to-left function composition: compose(f, g)(x) == f(g(x)).
pipe Pass a value through functions left to right.
once Decorator: run fn only the first time; later calls return the first result.
retry Decorator: retry on the given exceptions with exponential backoff.
timed Decorator: store the last run time (seconds) on wrapper.last_seconds.
memoize Cache results by arguments. For real code prefer functools.cache.
ttl_cache Decorator: cache results for seconds before recomputing.
curry Call a function one argument (or a few) at a time.
rate_limited Decorator: space calls so they never exceed calls_per_second.

Iterators and generators

Full code and examples: docs/iterators.md

Snippet What it does
take First n items of any iterable as a list.
batched Yield tuples of up to n items (itertools.batched exists in 3.12+).
pairwise Consecutive overlapping pairs (itertools.pairwise exists in 3.10+).
interleave Round-robin items from several iterables until all are exhausted.
run_length Run-length encode: (value, count) for each run of equal values.
flatten_iter Lazily chain an iterable of iterables.
nth The item at index n of any iterable, or default.
ilen Count items of an iterator without building a list.
peek Look at the first item and get back an iterator that still includes it.

Dates and times

Full code and examples: docs/dates.md

Snippet What it does
utc_now Current time as an aware UTC datetime (datetime.utcnow() is deprecated).
parse_iso Parse an ISO 8601 timestamp; a trailing ‘Z’ is accepted on every Python 3.7+.
days_between Whole days from date a to date b (negative if b is earlier).
add_business_days Add n weekdays (Mon-Fri) to a date. Holidays are not considered.
date_range Dates from start up to and including end.
is_leap_year Gregorian leap year rule.
age Age in whole years on today.
human_duration Readable duration like ‘1h 2m 3s’.
start_of_week Monday of the week containing d.

Files and paths

Full code and examples: docs/files.md

Snippet What it does
read_lines Lines of a text file without trailing newlines.
write_atomic Write a file so readers never see a half-written version.
load_json Read JSON, returning default if the file does not exist.
sha256_file SHA-256 of a file, read in chunks so big files are fine.
find_files Recursively list files matching a glob, skipping noisy folders.
dir_size Total size in bytes of every file under path.
ensure_dir Create a folder (and parents) if missing; return it as a Path.

Concurrency and asyncio

Full code and examples: docs/concurrency.md

Snippet What it does
parallel_map Run fn over items on a thread pool (good for I/O), keeping order.
gather_limited Await coroutines with at most limit running at once; results keep order.
with_timeout Await coro but give up after seconds and return default.
run_sync Run a coroutine from regular code (no running event loop required).

Built-in one-liners worth knowing

Before writing a helper, check whether Python already has it. These all run on Python 3.9+ unless noted.

Task One-liner
Reverse a list or string items[::-1]
Count occurrences collections.Counter(words).most_common(3)
Merge two dicts (3.9+) merged = a \| b
Update a dict in place (3.9+) a \|= b
Remove a prefix (3.9+) "v1.2".removeprefix("v")
Default dict values d.setdefault(key, []).append(x)
Sort by several keys sorted(people, key=lambda p: (p.last, p.first))
Sort descending by number sorted(rows, key=lambda r: -r.score)
Index while looping for i, x in enumerate(items, start=1):
Loop two lists together for a, b in zip(xs, ys, strict=True): (3.10+, raises if lengths differ)
Any / all any(x < 0 for x in nums), all(map(str.isdigit, parts))
Min / max by key max(files, key=os.path.getsize)
Swap variables a, b = b, a
Unpack head and tail first, *rest = items
Conditional expression label = "even" if n % 2 == 0 else "odd"
Assign inside a condition while (line := f.readline()):
Debug print with names print(f"{user_id=}, {elapsed=:.2f}")
Thousands separator f"{1234567:,}" gives '1,234,567'
Percent format f"{0.256:.1%}" gives '25.6%'
Zero padding f"{7:03d}" gives '007'
Integer square root math.isqrt(99) gives 9
Product of numbers (3.8+) math.prod([2, 3, 4]) gives 24
Ceiling division -(-a // b)
Read a whole file Path("a.txt").read_text(encoding="utf-8")
Current UTC time datetime.now(timezone.utc)
Cache a pure function @functools.cache (3.9+) or @functools.lru_cache(maxsize=None)
Flatten one level list(itertools.chain.from_iterable(nested))
Group consecutive items itertools.groupby(sorted(rows, key=f), key=f)
Unique, keep order list(dict.fromkeys(items))
Pretty print JSON json.dumps(obj, indent=2, ensure_ascii=False)
Random choice / sample random.choice(xs), random.sample(xs, k=3)
Secure token secrets.token_urlsafe(32)
Temporary directory with tempfile.TemporaryDirectory() as d:
Run a shell command subprocess.run(["ls", "-l"], check=True, capture_output=True, text=True)

Common Python gotchas

Short traps that cost people hours. Each one is a 30-second read.

Mutable default arguments are shared between calls.

def add(item, bucket=[]):        # the same list every call
    bucket.append(item)
    return bucket

def add(item, bucket=None):      # fix
    bucket = [] if bucket is None else bucket
    bucket.append(item)
    return bucket

[[0] * 3] * 3 copies the same inner list three times.

grid = [[0] * 3] * 3
grid[0][0] = 1        # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
grid = [[0] * 3 for _ in range(3)]   # fix: build each row

Closures capture variables, not values.

funcs = [lambda: i for i in range(3)]
[f() for f in funcs]                  # [2, 2, 2]
funcs = [lambda i=i: i for i in range(3)]
[f() for f in funcs]                  # [0, 1, 2]

Floats are binary. 0.1 + 0.2 == 0.3 is False. Use math.isclose for comparisons and decimal.Decimal("0.1") for money.

is checks identity, not equality. Use == for values and keep is for None, True and False.

Modifying a list while looping over it skips items. Loop over a copy (for x in items[:]) or build a new list with a comprehension.

Naming a file after a standard library module breaks imports. A local random.py, json.py or numbers.py shadows the real module. (This repo learned that the hard way: the math snippets live in numeric.py, not numbers.py.)

datetime.utcnow() returns a naive datetime and is deprecated since 3.12. Use datetime.now(timezone.utc).

round() uses banker’s rounding. round(2.5) is 2 and round(3.5) is 4. Use decimal with ROUND_HALF_UP if you need school rounding.

Default open() encoding depends on the platform. Always pass encoding="utf-8" for text files.

Catching bare except: also catches KeyboardInterrupt and SystemExit. Catch Exception or something more specific.

String concatenation in a loop is quadratic for large inputs. Collect parts in a list and "".join(parts).

FAQ

Can I use these snippets in commercial projects? Yes. The code is MIT licensed: copy it, change it, ship it. Keeping the license notice is appreciated when you copy large parts.

Why not just install a utility library? For one or two helpers, a ten-line function you can read is often better than a new dependency. For heavy use of iterator tools, libraries such as more-itertools and toolz are good choices.

Which Python version do I need? Python 3.9 or newer. A few snippets mention newer built-ins (for example itertools.batched in 3.12) that you can use instead when you are on a newer version.

Are these snippets fast? They favor clarity, but most use the fastest idiomatic approach (built-ins, comprehensions, dict.fromkeys, itertools). For heavy numerical work, use NumPy or pandas instead.

How do I run only one module’s examples? python3 -m doctest -v snippets/strings.py runs the examples in one file.

How is this different from a Python cheat sheet? A cheat sheet lists syntax; this is a library of small, tested functions that solve concrete tasks, plus a cheat sheet of built-in one-liners at the end.

Where to go next

Contributing

PRs are welcome. A good snippet:

  1. Solves one everyday task in a few lines, using only the standard library.
  2. Has a one-sentence docstring summary and at least one >>> example.
  3. Adds edge-case tests in tests/test_edge_cases.py if the docstring cannot show them.
  4. Passes python3 -m unittest after you run python3 scripts/build_readme.py.

Keep entries accurate: if a snippet duplicates something the standard library already provides, say so in the docstring.

License

Code is released under the MIT License.

If this helped you, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.