Get most significant digit in python

Nicky Feller picture Nicky Feller · Nov 26, 2015 · Viewed 7.9k times · Source

Say I have list [34523, 55, 65, 2]

What is the most efficient way to get [3,5,6,2] which are the most significant digits. If possible without changing changing each to str()?

Answer

senshin picture senshin · Nov 26, 2015

Assuming you're only dealing with positive numbers, you can divide each number by the largest power of 10 smaller than the number, and then take the floor of the result.

>>> from math import log10, floor
>>> lst = [34523, 55, 65, 2]
>>> [floor(x / (10**floor(log10(x)))) for x in lst]
[3, 5, 6, 2]

If you're using Python 3, instead of flooring the result, you can use the integer division operator //:

>>> [x // (10**floor(log10(x))) for x in lst]
[3, 5, 6, 2]

However, I have no idea whether this is more efficient than just converting to a string and slicing the first character. (Note that you'll need to be a bit more sophisticated if you have to deal with numbers between 0 and 1.)

>>> [int(str(x)[0]) for x in lst]
[3, 5, 6, 2]

If this is in a performance-critical piece of code, you should measure the two options and see which is faster. If it's not in a performance-critical piece of code, use whichever one is most readable to you.