How to find the length of a number in python

It's been several years since this question was asked, but I have compiled a benchmark of several methods to calculate the length of an integer.

def libc_size(i): 
    return libc.snprintf(buf, 100, c_char_p(b'%i'), i) # equivalent to `return snprintf(buf, 100, "%i", i);`

def str_size(i):
    return len(str(i)) # Length of `i` as a string

def math_size(i):
    return 1 + math.floor(math.log10(i)) # 1 + floor of log10 of i

def exp_size(i):
    return int("{:.5e}".format(i).split("e")[1]) + 1 # e.g. `1e10` -> `10` + 1 -> 11

def mod_size(i):
    return len("%i" % i) # Uses string modulo instead of str(i)

def fmt_size(i):
    return len("{0}".format(i)) # Same as above but str.format

(the libc function requires some setup, which I haven't included)

size_exp is thanks to Brian Preslopsky, size_str is thanks to GeekTantra, and size_math is thanks to John La Rooy

Here are the results:

Time for libc size:      1.2204 μs
Time for string size:    309.41 ns
Time for math size:      329.54 ns
Time for exp size:       1.4902 μs
Time for mod size:       249.36 ns
Time for fmt size:       336.63 ns
In order of speed (fastest first):
+ mod_size (1.000000x)
+ str_size (1.240835x)
+ math_size (1.321577x)
+ fmt_size (1.350007x)
+ libc_size (4.894290x)
+ exp_size (5.976219x)

(Disclaimer: the function is run on inputs 1 to 1,000,000)

Here are the results for sys.maxsize - 100000 to sys.maxsize:

Time for libc size:      1.4686 μs
Time for string size:    395.76 ns
Time for math size:      485.94 ns
Time for exp size:       1.6826 μs
Time for mod size:       364.25 ns
Time for fmt size:       453.06 ns
In order of speed (fastest first):
+ mod_size (1.000000x)
+ str_size (1.086498x)
+ fmt_size (1.243817x)
+ math_size (1.334066x)
+ libc_size (4.031780x)
+ exp_size (4.619188x)

As you can see, mod_size (len("%i" % i)) is the fastest, slightly faster than using str(i) and significantly faster than others.

Get the length of an Integer in Python #

To get the length of an integer in Python:

  1. Use the str() class to convert the integer to a string, e.g. result = str(my_int).
  2. Pass the string to the len() function, e.g. len(my_str).
  3. 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.

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.

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.

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 - {expression}.

How do you find the length of a number?

Perhaps the easiest way of getting the number of digits in an Integer is by converting it to String, and calling the length() method. This will return the length of the String representation of our number: int length = String. valueOf(number).

What does Len () do in Python?

The len() function returns the number of items in an object. When the object is a string, the len() function returns the number of characters in the string.

What does range () do in Python?

Python range() Function The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.

How do I find the length of a list in Python?

Python has got in-built method – len() to find the size of the list i.e. the length of the list. The len() method accepts an iterable as an argument and it counts and returns the number of elements present in the list.