- How to Get the Length of an Integer in Python?
- Converting to String and Checking the Length
- Converting to list and Checking the Length
- Looping and Removing Digits Off the End
- Calculating the Number of Digits
- Length of integer python
- # Table of Contents
- # Get the length of an Integer in Python
- # Handling possibly negative numbers
- # Get the length of an integer without conversion to string
- # Handling negative numbers when using math.log10
- # If you consider 0 to have a length of 0
- # Get the length of an Integer using a formatted string literal
- # Get the length of a Float in Python
- # Not counting the decimal
- # Handling negative floating-point numbers
- # Using a formatted string literal to get the length of a float
- # Additional Resources
How to Get the Length of an Integer in Python?
You can get the length of an integer in Python in any of the following ways:
Converting to String and Checking the Length
If you have a positive integer, you can do the following:
num = 12345 num_str = str(num) print(len(num_str)) # 5
If the number can potentially be negative, then you must first get the absolute value of the integer:
num = -12345 num_str = str(abs(num)) print(len(num_str)) # 5
To make it reusable, you could make this into a function, for example, like so:
def num_length(num): return len(str(abs(num))) print(num_length(0)) # 1 print(num_length(12345)) # 5 print(num_length(-12345)) # 5 print(num_length(9999999999999999999999999)) # 25 print(num_length(-9999999999999999999999999)) # 25
Converting to list and Checking the Length
If you have a positive integer, you can do the following:
- Convert integer to a list of digits;
- Call the len() method on the resulting list of digits.
For example, you can do this using list comprehension like so:
num = 12345 digits = [int(x) for x in str(num)] print(len(digits)) # 5
You can rewrite the same code using map() like so:
num = 12345 digits = list(map(int, str(num))) print(len(digits)) # 5
If the number can potentially be negative, then you must first get the absolute value of the integer:
num = -12345 digits = [int(x) for x in str(abs(num))] print(len(digits)) # 5
To make it reusable, you could make this into a function, for example, like so:
def num_length(num): digits = [int(x) for x in str(abs(num))] return len(digits) print(num_length(0)) # 1 print(num_length(12345)) # 5 print(num_length(-12345)) # 5 print(num_length(9999999999999999999999999)) # 25 print(num_length(-9999999999999999999999999)) # 25
Looping and Removing Digits Off the End
If you have a positive or a negative integer, you can do the following:
- Create a loop, and remove the last digit from the number in each iteration till there are no digits left;
- In each iteration, increment a counter, which would give the total number of digits in the number.
def num_length(num): num = abs(num) length = 0 while True: length += 1 num = num // 10 if num == 0: break return length print(num_length(0)) # 1 print(num_length(12345)) # 5 print(num_length(-12345)) # 5 print(num_length(9999999999999999999999999)) # 25 print(num_length(-9999999999999999999999999)) # 25
Calculating the Number of Digits
You should use this method with caution as it may give you the wrong result for really large numbers (such as 9999999999999999999999999 ).
If you have a positive integer, you can do the following:
- Calculate the log10 of the number, convert it to an integer and add 1 to the result;
- If the number is 0 , then return 1 as a count (because log10(0) equals -inf ).
import math num = 12345 length = 1 if num == 0 else int(math.log10(num)) + 1 print(length) #=> 5
If the number can potentially be negative, then you must first get the absolute value of the integer:
import math num = -12345 length = 1 if num == 0 else int(math.log10(abs(num))) + 1 print(length) #=> 5
To make it reusable, you could make this into a function, for example, like so:
import math def num_length(num): return 1 if num == 0 else int(math.log10(abs(num))) + 1 print(num_length(0)) # 1 print(num_length(12345)) # 5 print(num_length(-12345)) # 5 // this may give wrong result for really large numbers print(num_length(9999999999999999999999999)) # 26 print(num_length(-9999999999999999999999999)) # 26
Hope you found this post useful. It was published 04 Jan, 2023 . Please show your love and support by sharing this post.
Length of integer python
Last updated: Feb 18, 2023
Reading time · 4 min
# Table of Contents
# Get the length of an Integer in Python
To get the length of an integer in Python:
- Use the str() class to convert the integer to a string.
- Pass the string to the len() function, e.g. len(my_str) .
- The len() function will return the length of the string.
Copied!my_int = 1234 my_str = str(my_int) print(len(my_str)) # 👉️ 4
The len() function returns the length (the number of items) of an object.
The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).
This is why we had to convert the integer to a string — we can’t pass an integer to the len() function as integers are not a sequence or a collection.
# Handling possibly negative numbers
If you need to handle a scenario where the number is negative, subtract 1 from the result.
Copied!my_int = -1234 if my_int 0: result = len(str(my_int)) - 1 else: result = len(str(my_int)) print(result) # 👉️ 4
We check if the integer is less than 0 , and if it is, we subtract 1 from its length to account for the minus — sign.
# Get the length of an integer without conversion to string
You can use the math.log10() method to get the length of an integer without converting it to a string.
Copied!import math def get_integer_length(integer): return int(math.log10(integer)) + 1 print(get_integer_length(100)) # 👉️ 3 print(get_integer_length(12345)) # 👉️ 5
The math.log10 method returns the base-10 logarithm of the supplied number.
Copied!import math print(math.log10(100)) # 2.0 print(math.log10(12345)) # 4.091491094267951
The log10() method cannot be invoked with a negative number or 10 , otherwise, and error is raised.
# Handling negative numbers when using math.log10
If you need to handle negative numbers, make sure to only call the math.log10() method if the supplied number is greater than 0 .
Copied!import math def get_integer_length(integer): if integer > 0: return int(math.log10(integer)) + 1 elif integer == 0: return 1 else: return int(math.log10(-integer)) + 2 print(get_integer_length(100)) # 3 print(get_integer_length(12345)) # 5 print(get_integer_length(-1234)) # 5 print(get_integer_length(0)) # 1
If the given number is equal to 0 , we return that it has a length of 1 .
If the number is positive, we use the math.log10 method to get its length.
If the number is negative, we prefix it with a minus — sign to convert it to a positive number before calling math.log10 .
If you don’t want to count the minus — sign in the result, add 1 to the result of calling math.log10() if the number is negative.
Copied!import math def get_integer_length(integer): if integer > 0: return int(math.log10(integer)) + 1 elif integer == 0: return 1 else: return int(math.log10(-integer)) + 1 # 👈️ add 1 print(get_integer_length(-12)) # 2 print(get_integer_length(-1234)) # 4
The function above doesn’t include the minus — sign in the length of negative numbers.
# If you consider 0 to have a length of 0
If your application considers the number 0 to have a length of 0 , add an elif statement to check for 0 .
Copied!my_int = 0 if my_int 0: result = len(str(my_int)) - 1 elif my_int == 0: result = 0 else: result = len(str(my_int)) print(result) # 👉️ 0
The if statement checks if the number is less than 0 , and if it is, it subtracts 1 .
The elif statement checks if the number is equal to 0 , and if it is, we assign 0 to the result variable.
If the else statement runs, the integer is positive, so we can convert it to a string and pass the string to the len() function.
# Get the length of an Integer using a formatted string literal
You can also use a formatted string literal to get the length of an integer.
Copied!my_int = 123 result = len(f'my_int>') print(result) # 👉️ 3
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .
Copied!my_str = 'is subscribed:' my_bool = True result = f'my_str> my_bool>' print(result) # 👉️ is subscribed: True
Make sure to wrap expressions in curly braces — .
# Get the length of a Float in Python
If you need to get the length of a float:
- Use the str() class to convert the float to a string.
- Pass the string to the len() function, e.g. len(result) .
- The len() function will return the length of the string.
Copied!my_float = 3.14 my_str = str(my_float) print(len(my_str)) # 👉️ 4 without_counting_decimal = len(my_str) - 1 print(without_counting_decimal) # 👉️ 3
The len() function returns the length (the number of items) of an object.
The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).
This is why we had to convert the floating-point number to a string — we can’t pass a float to the len() function as floats are not a sequence or a collection.
# Not counting the decimal
If you don’t want to count the decimal, either subtract 1 from the result or replace it with an empty string.
Copied!my_float = 3.14 my_str = str(my_float) print(len(my_str)) # 👉️ 4 no_decimal_1 = len(my_str) - 1 print(no_decimal_1) # 👉️ 3 no_decimal_2 = len(my_str.replace('.', '')) print(no_decimal_2) # 👉️ 3
We used the str.replace() method to remove the decimal from the string by replacing it with an empty string.
# Handling negative floating-point numbers
If you need to handle a scenario where the number is negative, subtract 1 from the result.
Copied!my_float = 3.14 if my_float 0: result = len(str(my_float)) - 1 else: result = len(str(my_float)) print(result) # 👉️ 4
We check if the float is less than 0 , and if it is, we subtract 1 from its length to account for the minus — sign.
# Using a formatted string literal to get the length of a float
You can also use a formatted string literal to get the length of a float.
Copied!my_float = 3.14 result = len(f'my_float>') print(result) # 👉️ 4
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .
Copied!my_str = 'is subscribed:' my_bool = True result = f'my_str> my_bool>' print(result) # 👉️ is subscribed: True
Make sure to wrap expressions in curly braces — .
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.