fluttersmith/py-snippetsGitHub ↗

Split a number into its digits

Turn an integer into a list of its decimal digits.

Numbers#conversionO(d) time✓ 3 examples pass on 3.11–3.14

Checksums, digit sums and number puzzles all start here.

digitize.py✓ ruff · mypy --strict
def digitize(n: int) -> list[int]:
    """Return the decimal digits of ``n``, ignoring its sign."""
    return [int(digit) for digit in str(abs(n))]
  1. str(-405) has a "-" that int() can't parse, so drop the sign first
examples✓ 3 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> digitize(123)[1, 2, 3]passed on Python 3.11 to 3.14: >>> digitize(-405)[4, 0, 5]passed on Python 3.11 to 3.14: >>> digitize(0)[0]
Edit the function or the examples and run the doctests here, on Python 3.14. Python loads only when you click (about 7 MB, cached after the first time).

How it works

  • str() gives the decimal digits as text.
  • abs() comes first: int('-') would raise.
  • Each character converts back with int().

Complexity: O(d) time and space for d digits

Importfrom pysnippets.numbers.digitize import digitizeNo dependencies: copy digitize.py into your project, or clone the repo.

Adapted from digitize in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Handles negative numbers; typed. Suggest an edit.