fluttersmith/py-snippetsGitHub ↗
Cheat sheet · 22 rows · every proof runs in CI

The stdlib already does this.

Before you paste a helper, check here. Each row is a function people keep rewriting, and the standard library tool that already does it. The proof under each one is a doctest, run on Python 3.11–3.14.

22 rows
Instead of writing…Use…Since
Instead of chunk(items, size)replaces chunkuse itertools.batched(items, size)Yields tuples, lazily. On 3.13+, strict=True raises if the last batch is short.
>>> from itertools import batchedpassed on Python 3.12 to 3.14: >>> list(batched("abcdefg", 3))[('a', 'b', 'c'), ('d', 'e', 'f'), ('g',)]
3.12+
Instead of flatten(lists)replaces flattenuse itertools.chain.from_iterable(lists)Flattens one level, lazily. For any depth, see the deep_flatten snippet.
>>> from itertools import chainpassed on Python 3.11 to 3.14: >>> list(chain.from_iterable([[1, 2], [3], [], [4, 5]]))[1, 2, 3, 4, 5]
3.11+
Instead of gcd(numbers) / lcm(numbers)replaces gcd, lcmuse math.gcd(*numbers) / math.lcm(*numbers)Both take any number of arguments.
>>> import mathpassed on Python 3.11 to 3.14: >>> math.gcd(8, 36, 28), math.lcm(4, 6, 10)(4, 60)
3.11+
Instead of average(*args)replaces averageuse statistics.mean(values)statistics.fmean is faster and always returns a float.
>>> from statistics import fmean, meanpassed on Python 3.11 to 3.14: >>> mean([1, 2, 3, 4]), fmean([1, 2, 3, 4])(2.5, 2.5)
3.11+
Instead of median(values)replaces medianuse statistics.median(values)Unlike the hand-rolled version, it doesn't sort your list in place.
>>> from statistics import median>>> values = [7, 1, 5, 3]passed on Python 3.11 to 3.14: >>> median(values), values(4.0, [7, 1, 5, 3])
3.11+
Instead of factorial(n)replaces factorialuse math.factorial(n)Exact for any size, and raises ValueError for negative n.
>>> import mathpassed on Python 3.11 to 3.14: >>> math.factorial(10)3628800
3.11+
Instead of binomial_coefficient(n, k)replaces binomial-coefficientuse math.comb(n, k)math.perm(n, k) counts ordered arrangements.
>>> import mathpassed on Python 3.11 to 3.14: >>> math.comb(8, 2), math.perm(8, 2)(28, 56)
3.11+
Instead of cumsum(values)replaces cumsumuse itertools.accumulate(values)Pass a function for running products, maxima and so on.
>>> from itertools import accumulate>>> import operatorpassed on Python 3.11 to 3.14: >>> list(accumulate([1, 2, 3, 4])), list(accumulate([1, 2, 3, 4], operator.mul))([1, 3, 6, 10], [1, 2, 6, 24])
3.11+
Instead of frequencies(items) / count_occurrences(items, value)replaces frequencies, count-occurrencesuse collections.Counter(items)A missing value counts as 0 instead of raising KeyError.
>>> from collections import Counter>>> counts = Counter("mississippi")passed on Python 3.11 to 3.14: >>> counts["s"], counts["z"], counts.most_common(2)(4, 0, [('i', 4), ('s', 4)])
3.11+
Instead of max_n(items, n) / min_n(items, n)replaces max-n, min-nuse heapq.nlargest(n, items) / heapq.nsmallest(n, items)Both take key=, and beat a full sort when n is small.
>>> import heapqpassed on Python 3.11 to 3.14: >>> heapq.nlargest(2, [4, 1, 9, 7]), heapq.nsmallest(2, ["bb", "a", "ccc"], key=len)([9, 7], ['a', 'bb'])
3.11+
Instead of degrees_to_rads(deg) / rads_to_degrees(rad)replaces degrees-to-rads, rads-to-degreesuse math.radians(deg) / math.degrees(rad)
>>> import mathpassed on Python 3.11 to 3.14: >>> math.radians(180) == math.pi, math.degrees(math.pi / 2)(True, 90.0)
3.11+
Instead of to_binary(n) / to_hex(n)replaces to-binary, to-hexuse bin(n) / hex(n), or format(n, "b") / format(n, "x")format and f-strings drop the prefix and can pad: f"{n:08b}".
passed on Python 3.11 to 3.14: >>> bin(10), hex(255), f"{10:08b}", f"{255:x}"('0b1010', '0xff', '00001010', 'ff')
3.11+
Instead of sum_by(items, fn)replaces sum-byuse sum(fn(x) for x in items)A generator expression; no list is built.
passed on Python 3.11 to 3.14: >>> sum(len(word) for word in ["one", "three"])8
3.11+
Instead of merge_dictionaries(a, b)replaces merge-dictionariesuse a | bThe right-hand side wins on shared keys. a |= b updates in place.
passed on Python 3.11 to 3.14: >>> {"a": 1, "b": 2} | {"b": 3, "c": 4}{'a': 1, 'b': 3, 'c': 4}
3.11+
Instead of transpose(matrix)replaces transposeuse list(zip(*matrix))Rows come back as tuples; add strict=True to reject ragged input.
passed on Python 3.11 to 3.14: >>> list(zip(*[[1, 2, 3], [4, 5, 6]]))[(1, 4), (2, 5), (3, 6)]
3.11+
Instead of powerset(items)replaces powersetuse the itertools powerset recipeFrom the itertools docs. It yields subsets lazily, smallest first.
>>> from itertools import chain, combinations>>> s = [1, 2, 3]passed on Python 3.11 to 3.14: >>> list(chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)))[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
3.11+
Instead of roll(items, offset)replaces rolluse collections.deque.rotate(offset)In place and O(k), where k is the offset.
>>> from collections import deque>>> d = deque([1, 2, 3, 4, 5])>>> d.rotate(2)passed on Python 3.11 to 3.14: >>> ddeque([4, 5, 1, 2, 3])
3.11+
Instead of reverse(items)replaces reverseuse items[::-1] or reversed(items)Slicing copies; reversed() is a lazy view.
passed on Python 3.11 to 3.14: >>> [1, 2, 3][::-1], "abc"[::-1], list(reversed(range(3)))([3, 2, 1], 'cba', [2, 1, 0])
3.11+
Instead of zip(items, items[1:])use itertools.pairwise(items)Works on any iterable, not only sequences, and copies nothing.
>>> from itertools import pairwisepassed on Python 3.11 to 3.14: >>> [b - a for a, b in pairwise([1, 4, 9, 16])][3, 5, 7]
3.11+
Instead of a hand-written memo dictuse @functools.cacheUnbounded. Use @functools.lru_cache(maxsize=...) to cap memory.
>>> from functools import cache>>> @cache... def fib(n):...     return n if n < 2 else fib(n - 1) + fib(n - 2)passed on Python 3.11 to 3.14: >>> fib(80)23416728348467685
3.11+
Instead of abs(a - b) < 0.0001use math.isclose(a, b)Relative tolerance by default; pass abs_tol when comparing to zero.
>>> import mathpassed on Python 3.11 to 3.14: >>> 0.1 + 0.2 == 0.3, math.isclose(0.1 + 0.2, 0.3)(False, True)
3.11+
Instead of truncate(text, width)use textwrap.shorten(text, width)Cuts at a word boundary and collapses whitespace.
>>> import textwrappassed on Python 3.11 to 3.14: >>> textwrap.shorten("The quick brown fox jumps", width=18)'The quick [...]'
3.11+

Linked names in the left column are the original snippets in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Each was replaced by the standard library call next to it. Not affiliated with 30 seconds of code.