In python, is there a command similar to len() which works on integers?
Thanks
In python, is there a command similar to len() which works on integers?
Thanks
If you want the length of an integer as in the number of digits in the integer you can always typecast it to string like str(133) and find its len like len(str(123)).
Assuming you are asking for the largest number you can store in an integer, the value is implementation dependent. I suggest that you don't think in that way when using python. In any case, quite a large value can be stored in a python 'integer'. Remember, Python uses duck typing!
Edit: I gave my answer before the clarification that the asker wanted the number of digits. For that, I agree with the method suggested by the accepted answer. Nothing more to add!
Without conversion to string
import math
digits = int(math.log10(n))+1
To also handle zero and negative numbers
import math
if n > 0:
digits = int(math.log10(n))+1
elif n == 0:
digits = 1
else:
digits = int(math.log10(-n))+2 # +1 if you don't count the '-'
You'd probably want to put that in a function :)
Here are some benchmarks. The len(str())
is already behind for even quite small numbers
timeit math.log10(2**8)
1000000 loops, best of 3: 746 ns per loop
timeit len(str(2**8))
1000000 loops, best of 3: 1.1 µs per loop
timeit math.log10(2**100)
1000000 loops, best of 3: 775 ns per loop
timeit len(str(2**100))
100000 loops, best of 3: 3.2 µs per loop
timeit math.log10(2**10000)
1000000 loops, best of 3: 844 ns per loop
timeit len(str(2**10000))
100 loops, best of 3: 10.3 ms per loop
Python 2.*
int
s take either 4 or 8 bytes (32 or 64 bits), depending on your Python build. sys.maxint
(2**31-1
for 32-bit ints, 2**63-1
for 64-bit ints) will tell you which of the two possibilities obtains.
In Python 3, int
s (like long
s in Python 2) can take arbitrary sizes up to the amount of available memory; sys.getsizeof
gives you a good indication for any given value, although it does also count some fixed overhead:
>>> import sys
>>> sys.getsizeof(0)
12
>>> sys.getsizeof(2**99)
28
If, as other answers suggests, you're thinking about some string representation of the integer value, then just take the len
of that representation, be it in base 10 or otherwise!
from math import log10
digits = lambda n: ((n==0) and 1) or int(log10(abs(n)))+1