PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » Programs and Examples » Check Armstrong Number in Python

Check Armstrong Number in Python

Updated on: March 27, 2025 | Leave a Comment

An Armstrong Number (also known as a narcissistic number) is a number that is equal to the sum of its own digits raised to the power of the number of digits.

For example:

  • The number 153 is an Armstrong number because: 153 = 13 + 53 +33 = 1 + 125 + 27 = 153
  • The number 154 is NOT an Armstrong number because 154 = 13 + 53 +43 = 1 + 125 + 64 = 190

This article describes different methods to check if the number is Armstrong or not using Python.

Table of contents

  • 1. How to check Armstrong number in Python
  • 2. Using Mathematical Operation
  • 3. Using Recursion
  • 4. Using Python’s map and lambda functions
  • 5. Using List Comprehension
  • Summary

1. How to check Armstrong number in Python

Steps to check Armstrong number using loop and string conversion:

  1. Convert a number to a string

    Convert a number to a string using built-in str() function to access each digit individually.
    For Example, str(153) = '153'

  2. Count Digits in a number

    Determine the number of digits in the number using Python’s built-in len() function.
    For Example, len('153') = 3

  3. Calculate Sum of Powers

    Loop through each digit, convert it back to an integer, and raise it to the power of the total number of digits. The sum of these powers is accumulated.
    For Example, 153 = 13 + 53 +33 = 1 + 125 + 27 = 153

  4. Comparison

    The sum of powers is compared with the original number. If they are equal, the number is an Armstrong number.

Code Example:

# function to check armstrong number
def is_armstrong(number):
    # Convert the number to string to easily iterate over its digits
    digits = str(number)

    # Calculate the length (number of digits) of the number
    num_digits = len(digits)

    # Initialize a variable to store the sum of digits raised to the power of num_digits
    sum_of_powers = 0

    # Iterate over each digit and calculate its power
    for digit in digits:
        sum_of_powers += int(digit) ** num_digits

    # Check if the sum of powers is equal to the original number
    if sum_of_powers == number:
        return True
    else:
        return False

# function call
print(is_armstrong(153))    # True
print(is_armstrong(154))    # FalseCode language: Python (python)

2. Using Mathematical Operation

With this method, we check whether a number is an Armstrong number using mathematical operations like exponentiation (**), modulus (%), and floor division (//).

Code Example:

number = 153

# Store the original number
temp = number
# Calculate the number of digits
num_digits = len(str(number))
# Initialize sum to store the result of raising digits to powers
sum_of_powers = 0

# Iterate over the digits using mathematical operations
while temp > 0:
    digit = temp % 10  # Extract the last digit
    sum_of_powers += digit ** num_digits  # Raise it to the power of num_digits and add to sum
    temp //= 10  # Remove the last digit from temp

# Compare with the original number
is_armstrong = sum_of_powers == number
print(f"Is {number} an Armstrong number? : {is_armstrong}")

# Output:
# Is 153 an Armstrong number? : TrueCode language: Python (python)

Explanation:

  • Initial Variables:
    • number = 153: The number we’re testing to see if it’s an Armstrong number.
    • temp = number: A copy of the original number (153), used for calculations without changing the original value.
    • num_digits = len(str(number)): It converts the number to a string (“153”) and measures its length (3).
    • sum_of_powers = 0: This variable will store the sum of each digit raised to the power of num_digits.
  • While Loop:
    • The loop runs as long as temp is greater than 0. It extracts the digits of the number one by one and processes them:
    • digit = temp % 10: Extracts the last digit of temp. For 153, the last digit is 3.
    • sum_of_powers += digit ** num_digits: Raises the digit to the power of num_digits (3 in this case) and adds it to sum_of_powers. For 3, this would be 33 = 27
    • temp //= 10: Removes the last digit from temp by doing integer division. This reduces 153 to 15, then to 1, and eventually to 0.
  • Checking if Armstrong:
    • After the loop, the program compares sum_of_powers to the original number. If they are equal, the number is an Armstrong number; otherwise, it is NOT an Armstrong number.

3. Using Recursion

Recursion is a programming technique where a function calls itself to solve smaller instances of a problem until a base condition is met.

To check Armstrong number in Python, this method uses recursion to calculate the sum of the digits raised to the power of the number of digits.

Example Execution for 153:

153 = 13 + 53 +33 = 1 + 125 + 27 = 153

Recursion steps:

  1. 153 → last digit 3 → 3^3 = 27 → call sum_of_powers_recursive(15, 3)
  2. 15 → last digit 5 → 5^3 = 125 → call sum_of_powers_recursive(1, 3)
  3. 1 → last digit 1 → 1^3 = 1 → call sum_of_powers_recursive(0, 3)
  4. 0 → base case → return 0
  5. Summing up:
    1 + 125 + 27 = 153
  6. Compare the original number 153 to the summation output. If they are equal, then it’s an Armstrong number.

Code Example:

def sum_of_powers_recursive(number, num_digits):
    if number == 0:
        return 0
    else:
        # Extract the last digit and recursively sum powers
        return (number % 10) ** num_digits + sum_of_powers_recursive(number // 10, num_digits)

number = 153
num_digits = len(str(number))
is_armstrong = number == sum_of_powers_recursive(number, num_digits)
print(f"Is {number} an Armstrong number? : {is_armstrong}")

# Output:
# Is 153 an Armstrong number? : TrueCode language: Python (python)

Explanation:

  • The number of digits (num_digits) is calculated using len(str(number)).
  • sum_of_powers_recursive(number, num_digits):
    • This function takes a number (153) and the number of digits (3) as arguments.
    • If the number is 0, the recursion stops.
    • Otherwise,
      • It extracts the last digit (number % 10) (i.e., 153 % 10 = 3)
      • Raises it to the power of num_digits i.e., 33 = 27
      • Adds this value to the recursive call on the rest of the digits (number // 10) (i.e., 153 // 10 = 15).
      • And it continues till the number reaches 0.
    • It recursively calculates the sum of each digit raised to the power of the number of digits (33 + 53 + 13 ).
  • is_armstrong checks if the original number equals the sum of its digits raised to the power of the number of digits.
  • If true, the number is printed as an Armstrong number; otherwise, it is not.

4. Using Python’s map and lambda functions

This method leverages Python’s map() and sum() functions and a lambda expression for a concise solution to check if the given number is an Armstrong number.

  • A lambda function in Python is a small, anonymous function that can have multiple arguments but only one expression, which is evaluated and returned.
    For Example,
    square = lambda x: x ** 2
    print(square(5)) # Output: 25

  • The map() function in Python applies a given function to all items in an iterable (list, tuple, etc.) and returns a new iterator with the transformed values.
    For Example,
    squared = list(map(lambda x: x ** 2, [1, 2, 3, 4] ))
    print(squared) # Output: [1, 4, 9, 16]
  • The sum() function in Python returns the sum of all elements in an iterable (list, tuple, set, etc.).
    For Example,
    sum = sum(list(map(lambda x: x ** 2, [1, 2, 3, 4])))
    print (sum) # Output: [1, 4, 9, 16]

Code Example:

number = 153

num_digits = len(str(number))
is_armstrong = number == sum(map(lambda x: int(x) ** num_digits, str(number)))

print(f"Is {number} an Armstrong number? : {is_armstrong}")

# Output:
# Is 153 an Armstrong number? : TrueCode language: Python (python)

Explanation:

  • len(str(number)): It converts the number into string and calculates the length of the string, which tells us how many digits the number has. In this case, it returns 3, since ‘153’ has three characters.
  • sum(map(lambda x: int(x) ** num_digits, str(number))):
    • str(number): Again, this converts the number into a string so we can access each digit individually.
    • lambda x: int(x) ** num_digits: This is a small anonymous function (a lambda function) that takes each digit x (as a string), converts it to an integer, and raises it to the power of num_digits.
    • The map() function applies a lambda expression to each digit, which raises it to the power of the number of digits.
      So, for ‘153’, the map function will compute: 13=1, 53=125, 33=27
  • The sum() function adds up all the values produced by the map function.
    In this case, it calculates: 1 + 125 + 27 = 153
  • Finally, we check if the out from the sum() function is equal to the original number is equal to the original number. If they are equal, the result is True; otherwise, it is False.

5. Using List Comprehension

List comprehension is a concise way to create Python lists by applying an expression to each item in an iterable, with optional filtering using a condition.

In this approach, to check the Armstrong number, the logic is similar to the loop method using string conversion but uses list comprehension for a more Pythonic approach to find Armstrong numbers.

number = 153

num_digits = len(str(number))
# List comprehension to calculate the sum of digits raised to the power of num_digits
is_armstrong = number == sum([int(digit) ** num_digits for digit in str(number)])

print(f"Is {number} an Armstrong number? : {is_armstrong}")

# Output:
# Is 153 an Armstrong number? : TrueCode language: Python (python)

Explanation:

  • len(str(number)): It converts the number into string and calculates the length of the string, which tells us how many digits the number has. In this case, it returns 3, since ‘153’ has three characters.
  • [int(digit) ** num_digits for digit in str(number)]:
    • This is a list comprehension, which is a compact way to generate a list.
    • for digit in str(number): Loops through each character (digit) in the string representation of the number (‘153’). So, it loops over ‘1’, ‘5’, and ‘3’.
    • int(digit): Converts each character back into an integer.
    • int(digit) ** num_digits: Raises each digit to the power of num_digits (which is 3 in this case).
    • For 153, this list comprehension creates the list [1^3, 5^3, 3^3], which is [1, 125, 27].
  • The sum() function adds up all the values in the list.
    For [1, 125, 27], it calculates: 1 + 125 + 27 = 153
  • Finally, we check if the result from the sum() function is equal to the original number (i.e., if the sum of the digits raised to the power of num_digits is equal to the original number.) If they are equal, the result is True; otherwise, it is False.

Summary

This article explored diverse Python methods for determining if a number is an Armstrong number. It began with the foundational while loop approach, demonstrating how to extract digits and calculate their powers iteratively. It then transitioned to more Pythonic techniques, showcasing the power of string conversion and for loops for concise and efficient solutions. The article also touched upon the less common, but conceptually interesting, recursive implementation, highlighting the flexibility of Python’s function call mechanism.

These are different ways to determine whether a given number is an Armstrong number in Python. You can choose the one that best suits your requirements, whether it’s clarity, conciseness, or efficiency.

The Mathematical Operations approach is the most efficient in terms of time and space.

  • Loop and string conversion:
    • Advantage: Efficient, avoids recursion
  • Mathematical Operation:
    • Advantage: Efficient and avoids unnecessary string operations.
  • Recursion:
    • Advantage: Mimics the natural mathematical formula for Armstrong numbers.
  • map() function and lambda:
    • Advantage: Uses functional programming, making the code clean and compact.
  • List comprehension:
    • Advantage: Short and elegant, following a Pythonic approach.

Filed Under: Programs and Examples, Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Programs and Examples Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Programs and Examples Python Python Basics
TweetF  sharein  shareP  Pin

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com

Advertisement