PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
  • Quizzes
  • Code Editor
Home » Python » Programs and Examples » Count Digits of a Number in Python

Count Digits of a Number in Python

Updated on: March 27, 2025 | Leave a Comment

In this article, we have discussed different ways to count the number of digits in an integer in Python. Each method achieves the same result, showcasing the versatility of Python and programming techniques in general.

However, each program has its own time and space complexity, making it better. Let’s see the Python examples of each method individually.

Table of contents

  • 1. Using a Loop
  • 2. Using String Conversion
  • 3. Using Regular Expressions (regex)
  • 4. Using Logarithms
  • 5. Using Recursion
  • 6. Using List Comprehension and sum()
  • 7. Using len() on an Iterator
  • 8. Using the reduce() Function
  • 9. Using the map() Function
  • Summary

1. Using a Loop

while loop is the most straightforward to find the number of digits.

This is a classic iterative approach. We repeatedly divide the number by 10 (integer division) until it becomes 0. Each time we divide the number, the last digit is removed, and we keep count of it

Increment a counter in each iteration to count how often this operation is done before the number reaches 0.

Code Example

num = 123456
count = 0
while num != 0:
     num //= 10  # Integer division by 10 removes the last digit
     count += 1  # Increment the count for each digit removed
print("Number of digits:", count)Code language: Python (python)

Output:

Number of digits: 6Code language: Python (python)

Explanation

  • In each iteration, the original number num gets divided by 10 using Floor Division Assignment Operator (//=). It reduces the num by one digit.
    For example, (12345 //= 10) = 1234
  • Floor Division Assignment Operator (//=): It performs floor division (//) and assigns the result back to the variable in a single step, i.e., (num //= 10) is same as (num = num // 10)
  • The counter gets incremented with each digit.
  • The while loop iterates as long as the number is not zero.
  • The number of iterations corresponds to the number of digits in the original number.

2. Using String Conversion

This is a most Pythonic and easy-to-understand method for finding the length of an integer. We convert an integer number into a string and count each character using len() function.

Code Example

num = 123456
count = len(str(abs(num))) # Convert number to string and count its length
print("Number of digits:", count)

# Output:
# Number of digits: 6Code language: Python (python)

Explanation

  • abs(num) function: It returns the absolute value of num. Remove any negative signs and keep the number non-negative. For example, abs(-10) = 10
  • str() function: It converts a given value into a string (text) format. For example, str(123) = “123”
  • len() function: It returns the number of elements in an iterable (string, list, tuple, dictionary, etc.). For example, len(“123”) = 3

3. Using Regular Expressions (regex)

A Regular Expression (regex) in Python is a sequence of characters that defines a search pattern and is used for matching, searching, or manipulating strings efficiently.

This is another easy method in Python to find the length of an integer where we count the digits in a number using re.findall().

The re.findall() function in Python searches for all occurrences of a pattern in a string and returns them as a list.

Syntax: re.findall(pattern, string)

  • pattern → The regex pattern to search for.
  • string → The input text to search within.
  • Returns a list of all matches.

Code Example

import re

num = 123456
count = 0
count = len(re.findall(r'\d', str(abs(num))))  # Find all digit characters using regex
print("Number of digits:", count)

# Output:
# Number of digits: 6Code language: Python (python)

Explanation

  1. str(abs(num)): These functions return absolute integer numbers and convert them into strings.
  2. re.findall(): Searches each character in the string that matches the regex \d pattern and collects it into a list. \d is used to represent digits.
  3. len(): This is used to get the list size returned by re.findall() to get the final count of the digits in the number.

4. Using Logarithms

This approach uses logarithms to calculate the number of digits in an integer. This Python method is efficient for large numbers.

Here, we are using the following functions from math module:

  • math.log10(): It returns the base-10 logarithm of a given positive number. For example,
    math.log10(100) = 2.0 (Since 10² = 100)
    math.log10(1000) = 3.0 (Since 10³ = 1000)
  • math.floor(): The math.floor() function rounds a given number down to the nearest integer.
    For example, math.floor(4.9) = 4

Code Example

import math

num = 123456
count = 0
if num == 0:
    count = 1  # Special case for zero, which has one digit
else:
    count = math.floor(math.log10(abs(num))) + 1

print("Number of digits:", count)

# Output:
# Number of digits: 6Code language: Python (python)

Explanation

The logarithm base 10 of a number tells you how many times 10 must be multiplied to get the number. By taking the floor of this value and adding 1, you get the number of digits.

5. 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.

This is similar to the looping method to count the number of digits in an integer using recursion, we repeatedly remove the last digit from the number and count how many times we can do this until we reach 0.

For n = 12345

count_digits_recursive(12345) → 1 + count_digits_recursive(1234)
count_digits_recursive(1234) → 1 + count_digits_recursive(123)
count_digits_recursive(123) → 1 + count_digits_recursive(12)
count_digits_recursive(12) → 1 + count_digits_recursive(1)
count_digits_recursive(1) → 1 + count_digits_recursive(0)
count_digits_recursive(0) → 0 (Base Case)

Final Output: 5 (since 12345 has 5 digits)

Code Example

def count(num):
    num = abs(num)
    if num == 0:
        return 0  # Base case: no more digits to count
    return 1 + count(num // 10)

num = 123456
print("Number of digits:", count(num))

# Output:
# Number of digits: 6Code language: Python (python)

Explanation

The function calls itself with the number divided by 10, reducing the number by one digit each time. The base case occurs when the number becomes 0. The recursion depth corresponds to the number of digits.

6. Using List Comprehension and sum()

To find the number of digits, we are using list comprehension and sum() function in Python to count each character.

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.

The sum() function returns the total sum of all elements in an iterable (list, tuple, set, etc.).

Code Example

num = 123456
count = 0
count = sum(1 for _ in str(abs(num))) # Sum up 1 for each character in the string
print("Number of digits:", count)

# Output:
# Number of digits: 6Code language: Python (python)

Explanation

  • abs(num) → Takes the absolute value of num, ensuring it works for both positive and negative numbers.
    For Example, abs(-456) = 456
  • str(abs(num)) → Converts the absolute number into a string, allowing digit-wise iteration.
    For Example, str(456) = '456'
  • for _ in str(abs(num)) → Iterates over each character (digit) in the string representation of the number.
    For '456' iterate 3 times.
  • sum(1 for _ in str(abs(num))) → Adds 1 for each digit in the number, effectively counting the digits.
    For Example, sum(1 for _ in '456') = 1 + 1 + 1 = 3

7. Using len() on an Iterator

This is almost similar to the above method, where we have used len() function on the iterator instead of sum() to find the number of digits of a number using Python.

The len() function returns the number of elements in an iterable (string, list, tuple, dictionary, etc.).

Code Example

num = 123456
count = 0
count = len([_ for _ in str(abs(num))])  # Use len() to count the length of the list
print("Number of digits:", count)

# Output:
# Number of digits: 6Code language: Python (python)

Explanation

  • Here, a list is created by iterating over the characters in the string. The len() function then counts the number of elements in this list.
  • _ for _ in str(abs(num)) → A comprehension that simply collects each digit as a character.
    For Example,
    num = -456,
    [_ for _ in str(abs(-456))] = [_ for _ in '456'] = ['4', '5', '6']
    len(['4', '5', '6']) = 3

8. Using the reduce() Function

The reduce() function in Python applies a given function (lambda function) cumulatively to the elements of an iterable, reducing it to a single value.

A lambda function in Python is a small, anonymous function that can have multiple arguments but only one expression, which is evaluated and returned.

To count the length of a number in Python this method works by converting the integer to a string and then using reduce() to sum up 1 for each character (digit) in the string.

Code Example

from functools import reduce

num = 123456
count = 0
count = reduce(lambda x, y: x + 1, str(abs(num)), 0)
print("Number of digits:", count)

# Output:
# Number of digits: 6Code language: Python (python)

Explanation

reduce() iteratively applies the lambda function, which counts each character in the string by incrementing a counter. The reduce() function takes three arguments:

  1. lambda x, y: x + 1: This is a lambda function that takes two arguments x and y. It returns x + 1 each time it’s called. Here x is the accumulated value (starting with 0), and y is each character (digit) in the string.
  2. str(abs(num)): This is the iterable we are reducing, which is the string representation of the absolute value of num. If num = -123456, this will convert it to the string '123456'.
  3. 0: This is the initial value of the accumulator (x), which starts at 0.

9. Using the map() Function

The map() function in Python applies a given function to each item of an iterable, returning a new iterable with the results.

This method is similar to the above method the only difference is, we are using map() and sum() functions instead of reduce() and len() to count the digits in the number using Python.

Code Example

num = 123456
count = 0
count = sum(map(lambda x: 1, str(abs(num))))  # Map each character to 1 and sum them
print("Number of digits:", count)

# Output:
# Number of digits: 6Code language: Python (python)

Explanation

  1. str(abs(num)) : convert the number into string. For Example, str(abs(123)) = '123'
  2. lambda x: 1 : is an anonymous function that takes one argument x and always returns 1, no matter what x is.
  3. The map() function applies this lambda function to each character in the string, which returns 1 for each digit in the number.
    For example, if num is 123, then map(lambda x: 1, str(abs(123))) would produce an iterable like [1, 1, 1].
  4. The sum() function adds up all the 1s generated by the map() function.

Summary

Each method in Python that we discussed has its strengths and is chosen based on the specific needs of the problem. Like,

  • Loop Method is a straightforward approach suitable for understanding the basic concept of digit counting.
  • String Conversion methods are quick and easy to implement but convert the number into a string, which may not be ideal for large numbers.
  • Logarithms provide an efficient mathematical approach that is beneficial for very large numbers.
  • Recursion is a more conceptual approach and may not be ideal for large numbers due to recursion depth limits.
  • List Comprehension, reduce() and map() offer more functional programming approaches.
  • Regular Expressions add flexibility and can be extended to more complex digit extraction if needed.

Summary table of time and space complexity:

Here, 'n' is the value of the number and 'd' is the number of digits in the number. The logarithms method was the most time-efficient in terms of the time and space complexity of O(1).

MethodTime ComplexitySpace Complexity
LoopO(log₁₀(n))O(1)
String ConversionO(d)O(d)
Regular Expressions (regex)O(d)O(d)
LogarithmsO(1)O(1)
RecursionO(log₁₀(n))O(log₁₀(n))
List Comprehension + sum()O(d)O(d)
len() on IteratorO(d)O(d)
reduce() FunctionO(d)O(d)
map() FunctionO(d)O(d)

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

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 10 questions
  • Each Quiz contains 12-15 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.

Explore Python

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

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

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–2025 pynative.com

Advertisement