- Using Python to Split a Number into Digits
- Using Division and Remainders to Split a Number into Digits in Python
- Other Articles You’ll Also Like:
- About The Programming Expert
- Split number into digits python
- # Table of Contents
- # Split an integer into digits in Python
- # Split an integer into digits using a for loop
- # Split an integer into digits using map()
- # Split an integer into digits using math.ceil() and math.log()
- # Split an integer into digits using divmod
- # Additional Resources
- Split Integer Into Digits in Python
- Use List Comprehension to Split an Integer Into Digits in Python
- Use the math.ceil() and math.log() Functions to Split an Integer Into Digits in Python
Using Python to Split a Number into Digits
In Python, there are a number of ways we can split a number into digits. The easiest way to get the digits of an integer is to use list comprehension to convert the number into a string and get each element of the string.
def getDigits(num): return [int(x) for x in str(num)] print(getDigits(100)) print(getDigits(213)) #Output: [1,0,0] [2,1,3]
We can also get the digits of a number using a for loop in Python.
def getDigits(num): digits = [] for x in str(num): digits.append(int(x)) return digits print(getDigits(100)) print(getDigits(213)) #Output: [1,0,0] [2,1,3]
Another way is we can define a loop to get the remainder of the number after dividing by 10, divide by 10, and then continue the process until we collect all the digits.
def getDigits(num): digits = [] while num > 0: digits.append(num % 10) num = int(num/10) digits.reverse() return digits print(getDigits(100)) print(getDigits(213)) #Output: [1,0,0] [2,1,3]
When working with numbers in computer programming, it is useful to be able to easily extract information from our variables.
One such piece of information is the digits that a number is made up of. In Python, we can easily split a number into its digits.
The easiest way to get the digits of an integer in Python is to use list comprehension.
Using list comprehension, we convert the number into a string and get each element of the string.
def getDigits(num): return [int(x) for x in str(num)] print(getDigits(100)) print(getDigits(213)) #Output: [1,0,0] [2,1,3]
We can also get the digits of a number using a for loop in Python and applying the same logic as in the list comprehension code example.
def getDigits(num): digits = [] for x in str(num): digits.append(int(x)) return digits print(getDigits(100)) print(getDigits(213)) #Output: [1,0,0] [2,1,3]
Using Division and Remainders to Split a Number into Digits in Python
We can also split a number into digits using a method without converting the number into a string.
To get the digits of a number using division, we find the remainder of the number divided by 10. Then we will divide by 10, and continue the process until we hit 0.
Doing this method in Python is easy with a while loop.
Below is an example of a function for how to split a number into digits using a loop in Python.
def getDigits(num): digits = [] while num > 0: digits.append(num % 10) num = int(num/10) digits.reverse() return digits print(getDigits(100)) print(getDigits(213)) #Output: [1,0,0] [2,1,3]
Hopefully this article has been useful for you to learn how to split a number into digits in Python.
Other Articles You’ll Also Like:
- 1. Drop Last n Rows of pandas DataFrame
- 2. Squaring in Python – Square a Number Using Python math.pow() Function
- 3. pandas min – Find Minimum Value of Series or DataFrame
- 4. Python sinh – Find Hyperbolic Sine of Number Using math.sinh()
- 5. Get Random Value from Dictionary in Python
- 6. pandas Drop Rows – Delete Rows from DataFrame with drop()
- 7. Check if File Exists in AWS S3 Bucket Using Python
- 8. Python Random Boolean – How to Generate Random Boolean Values
- 9. for char in string – How to Loop Over Characters of String in Python
- 10. Using Python to Append Character to String Variable
About The Programming Expert
The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.
Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.
At the end of the day, we want to be able to just push a button and let the code do it’s magic.
You can read more about us on our about page.
Split number into digits python
Last updated: Feb 19, 2023
Reading time · 4 min
# Table of Contents
# Split an integer into digits in Python
To split an integer into digits:
- Use the str() class to convert the integer to a string.
- Use a list comprehension to iterate over the string.
- On each iteration, use the int() class to convert each substring to an integer.
Copied!an_int = 13579 list_of_digits = [int(x) for x in str(an_int)] print(list_of_digits) # 👉️ [1, 3, 5, 7, 9]
We used the str() class to convert the integer to a string, so we can iterate over the string.
The next step is to use a list comprehension to iterate over the string.
List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.
On each iteration, we pass the string to the int() class to convert it to an integer.
You can also use a simple for loop to achieve the same result.
# Split an integer into digits using a for loop
This is a three-step process:
- 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.
Copied!an_int = 13579 list_of_digits = [] for x in str(an_int): list_of_digits.append(int(x)) print(list_of_digits) # 👉️ [1, 3, 5, 7, 9]
We iterate over the digits that are wrapped in a string and on each iteration, we use the int() class to convert the value to an integer before appending the result to a list.
Alternatively, you can use the map() function to split an integer into digits.
# Split an integer into digits using map()
This is a three-step process:
- Use the str() class to convert the integer to a string.
- Pass the int class and the string to the map() function.
- Use the list() class to convert the map object to a list.
Copied!an_int = 13579 list_of_digits = list(map(int, str(an_int))) print(list_of_digits) # 👉️ [1, 3, 5, 7, 9]
The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.
Copied!an_int = 13579 a_str = str(an_int) list_of_digits = list(map(int, a_str)) print(list_of_digits) # 👉️ [1, 3, 5, 7, 9]
The int() class gets passed each substring from the string and converts the values to integers.
Note that the map() function returns a map object (not a list), so we have to use the list() class to convert the map object to a list.
# Split an integer into digits using math.ceil() and math.log()
You can also use the math.ceil() and math.log() methods if you need to split the integer into digits without converting to a string.
Copied!import math an_int = 13579 x = math.log(an_int, 10) y = math.ceil(x) list_of_digits = [(an_int//(10**i)) % 10 for i in range(y, -1, -1) ][bool(math.log(an_int, 10) % 1):] print(list_of_digits) # [1, 3, 5, 7, 9]
The math.ceil method returns the smallest integer greater than or equal to the provided number.
Copied!import math result_1 = math.ceil(25 / 4) print(result_1) # 👉️ 7 result_2 = 25 / 4 print(result_2) # 👉️ 6.25
The math.log() method returns the natural logarithm of a number.
You can also extract the logic into a reusable function.
Copied!import math def split_integer(an_int): x = math.log(an_int, 10) y = math.ceil(x) list_of_digits = [(an_int//(10**i)) % 10 for i in range(y, -1, -1) ][bool(math.log(an_int, 10) % 1):] return list_of_digits print(split_integer(12345)) # [1, 2, 3, 4, 5] print(split_integer(100)) # [1, 0, 0] print(split_integer(563)) # [5, 6, 3]
The split integer function takes an integer as a parameter and splits the integer into a list of digits.
The solution is quite difficult to read, however, it is a bit faster because it doesn’t require us to convert the value to a string.
# Split an integer into digits using divmod
If you need to split an integer into digits from right to left, use the divmod method.
Copied!an_int = 13579 list_of_digits = [] while an_int > 0: an_int, remainder = divmod(an_int, 10) list_of_digits.append(remainder) print(list_of_digits) # [9, 7, 5, 3, 1]
Notice that the result is produced from right to left.
The divmod function takes two numbers and returns a tuple containing 2 values:
- The result of dividing the first argument by the second.
- The remainder of dividing the first argument by the second.
On each iteration of the while loop, we use the divmod() function to get the result and the remainder of the division.
The remainder gets pushed into the list until the integer is equal to or less than 0 .
# 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.
Split Integer Into Digits in Python
- Use List Comprehension to Split an Integer Into Digits in Python
- Use the math.ceil() and math.log() Functions to Split an Integer Into Digits in Python
- Use the map() and str.split() Functions to Split an Integer Into Digits in Python
- Use a for Loop to Split an Integer Into Digits in Python
This tutorial will discuss different methods to split an integer into digits in Python.
Use List Comprehension to Split an Integer Into Digits in Python
List comprehension is a much shorter and graceful way to create lists that are to be formed based on given values of an already existing list.
In this method, str() and int() functions are also used along with List comprehension to split the integer into digits. str() and int() functions are used to convert a number to a string and then to an integer respectively.
The following code uses list comprehension to split an integer into digits in Python.
num = 13579 x = [int(a) for a in str(num)] print(x)
The number num is first converted into a string using str() in the above code. Then, list comprehension is used, which breaks the string into discrete digits. Finally, the digits are converted back to an integer using the int() function.
Use the math.ceil() and math.log() Functions to Split an Integer Into Digits in Python
The operation of splitting the integer into digits in Python can be performed without converting the number to string first. Moreover, this method is about twice as fast as converting it to a string first.
The math.ceil() function rounds off a number up to an integer. The math.log() function provides the natural logarithm of a number. To use both these functions, we should import the math library.
The math module can be defined as an always accessible and standard module in Python. It provides access to the fundamental C library functions.
The following code uses list comprehension, math.ceil() and math.log() functions to split an integer into digits in Python.
import math n = 13579 x = [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10))-1, -1, -1)] print(x)