To split an integer into digits:Use the str() class to convert the integer to a string. Use a for loop to iterate over the string. Use the int() class to convert each substring to an integer and append them to a list.
This can be done quite easily if you:
Use str
to convert the number into a string so that you can iterate over it.
Use a list comprehension to split the string into individual digits.
Use int
to convert the digits back into integers.
Below is a demonstration:
>>> n = 43365644
>>> [int(d) for d in str(n)]
[4, 3, 3, 6, 5, 6, 4, 4]
>>>
Here's a way to do it without turning it into a string first (based on some rudimentary benchmarking, this is about twice as fast as stringifying n
first):
>>> n = 43365644
>>> [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10))-1, -1, -1)]
[4, 3, 3, 6, 5, 6, 4, 4]
Updating this after many years in response to comments of this not working for powers of 10:
[(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][bool(math.log(n,10)%1):]
The issue is that with powers of 10 (and ONLY with these), an extra step is required. ---So we use the remainder in the log_10 to determine whether to remove the leading 0
--- We can't exactly use this because floating-point math errors cause this to fail for some powers of 10. So I've decided to cross the unholy river into sin and call upon regex.
In [32]: n = 43
In [33]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
Out[33]: [4, 3]
In [34]: n = 1000
In [35]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
Out[35]: [1, 0, 0, 0]
The easiest way is to turn the int into a string and take each character of the string as an element of your list:
>>> n = 43365644
>>> digits = [int(x) for x in str(n)]
>>> digits
[4, 3, 3, 6, 5, 6, 4, 4]
>>> lst.extend(digits) # use the extends method if you want to add the list to another
It involves a casting operation, but it's readable and acceptable if you don't need extreme performance.
If you want to change your number into a list of those numbers, I would first cast it to a string
, then casting it to a list will naturally break on each character:
[int(x) for x in str(n)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With