Home / Python / Example programs / Loops and numbers

Python program: Armstrong numbers

An Armstrong number equals the sum of its digits, each raised to the power of the number of digits (153 = 1³ + 5³ + 3³).

The code

def is_armstrong(n):
    digits = str(n)
    power = len(digits)
    return n == sum(int(d) ** power for d in digits)

print([n for n in range(1, 10_000) if is_armstrong(n)])

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474]

How it works

Converting to a string gives the digits and their count at once. A comprehension then finds every Armstrong number below 10,000.

Python features used

Learn the ideas behind it in the free lesson Pythonic Python.