Split Integer Into Digits in Python

Vaibhhav Khetarpal Nov 09, 2023
  1. Use List Comprehension to Split an Integer Into Digits in Python
  2. Use the math.ceil() and math.log() Functions to Split an Integer Into Digits in Python
  3. Use the map() and str.split() Functions to Split an Integer Into Digits in Python
  4. Use a for Loop to Split an Integer Into Digits in Python
  5. Conclusion
Split Integer Into Digits in Python

In this tutorial, we’ll explore different methods for splitting an integer into its individual digits in Python. We’ll discuss the following techniques to achieve this: using list comprehension, leveraging the math.ceil() and math.log() functions, employing the map() and str.split() functions, and creating a loop-based method.

Each method offers a unique approach to breaking down an integer into its constituent digits, catering to different programming scenarios and preferences.

Use List Comprehension to Split an Integer Into Digits in Python

List comprehension is a much shorter and more 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.

Basic Syntax:

x = [int(a) for a in str(num)]

Parameter:

  • num: This is the integer you want to split into its digits. It’s the input value for the list comprehension.

The syntax creates a new list by iterating through the characters of the string representation of the integer num. For each character a, the int() function is applied to convert it into an integer.

The result is a list x containing the individual digits of the original integer, where each character in the string becomes a separate element in the list.

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)

Output:

[1, 3, 5, 7, 9]

In the code, we start with the integer value 13579 stored in the variable num. To split this integer into its individual digits, we first convert it into a string using str(num), resulting in the string "13579".

Next, we use a list comprehension, [int(a) for a in str(num)], to iterate through each character in the string and convert it back to an integer using int(a). These integers are then stored in a list named x.

Finally, we print the contents of the list x, which gives us the output [1, 3, 5, 7, 9].

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 a 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, and 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.

Basic Syntax:

x = [(num // (10**i)) % 10 for i in range(places)]

Parameters:

  • num: This parameter represents the integer you want to split into its digits.
  • i: This variable is used within the list comprehension to iterate through a range of values, representing the positions of the digits in the integer.
  • places: The places parameter defines the number of digits in the integer, which determines the range of i values to consider during the iteration.

The syntax represents a concise way to split an integer num into its individual digits in Python. It accomplishes this by iterating through a range of values from 0 to places - 1, where each value corresponds to a digit’s position.

The expression (num // (10 ** i)) % 10 is applied for each position, effectively extracting the individual digit. These extracted digits are then collected in the list x, providing a compact and efficient method for breaking down an integer into its constituent digits.

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)

Output:

[1, 3, 5, 7, 9]

In the code, we begin by importing the math module to access mathematical functions and constants. The integer 13579 is assigned to the variable n, representing the number we aim to split into its individual digits.

Next, we utilize a list comprehension to iterate through a range of indices i, each corresponding to the position of a digit in the number. For each index, we calculate the digit’s value by dividing the original number n by 10 raised to the power of i, resulting in (n // (10 ** i)).

To isolate the individual digit, we take the remainder when dividing by 10, which is achieved with ((n // (10 ** i)) % 10). This process is executed for all relevant indices, as determined by the range generated using range(math.ceil(math.log(n, 10)) - 1, -1, -1).

All extracted digits are then stored in the list x. Finally, we print the contents of the list x, which reveals the individual digits of the original number, producing the output [1, 3, 5, 7, 9].

Use the map() and str.split() Functions to Split an Integer Into Digits in Python

The map() function implements a stated function for every item in an iterable. The item is then consigned as a parameter to the function.

The split() method, as the name suggests, is used to split a string into a list. It has a basic syntax and holds two parameters, the separator and the maxsplit.

The number needs to be already in the string format so that this method can be used.

Basic Syntax:

list1 = str1.split()
listofint = list(map(int, list1))

The parameter in the 1st line list1 = str1.split():

  • str1: This is the input string that you want to split into a list. It contains space-separated numbers.

The parameters in the next line listofint = list(map(int, list1)):

  • int: This is a built-in function used for converting a string to an integer.
  • list1: This is the list of strings obtained after splitting the input string using the split() method.

The second line uses the map() and int() functions to convert the string list to an integer list.

The following code uses the map() and str.split() functions to split an integer into digits in Python.

str1 = "1 3 5 7 9"
list1 = str1.split()
map_object = map(int, list1)

listofint = list(map_object)
print(listofint)

Output:

[1, 3, 5, 7, 9]

In this code, we begin with the string str1, which contains a sequence of space-separated numbers, specifically "1 3 5 7 9". To extract and work with these numbers as integers, we first use the split() method on str1, resulting in the creation of a list called list1.

The list1 now holds individual number strings, which are "1", "3", "5", "7", and "9". We proceed to apply the int function to each element within list1 using a map_object, effectively converting the strings to integers.

The resulting map object is then converted into a list called listofint. Finally, when we print listofint, the output showcases the integers from the original string, beautifully organized in the form of a list, displaying [1, 3, 5, 7, 9].

This code adeptly transforms a space-separated string of numbers into a list of integers for further processing or analysis.

Use a for Loop to Split an Integer Into Digits in Python

In this method, we use a loop and perform the slicing technique till the specified number of digits (A=1 in this case) and then finally, use the int() function for conversion into an integer.

The following code uses the int(), loop, and slice to split an integer into digits in Python.

str1 = "13579"
A = 1
result = []

for i in range(0, len(str1), A):
    result.append(int(str1[i : i + A]))
print("The resultant list : " + str(result))

Output:

The resultant list : [1, 3, 5, 7, 9]

In this code, we begin with the string str1 containing the sequence of numbers, specifically "13579". The variable A is initialized to 1, which dictates that we process the string character by character.

Next, we create an empty list named result to hold the individual digits that we’ll extract. To extract these digits, we utilize a for loop that iterates through the string.

Beginning at index 0 and advancing by A, which is 1 in this case, we extract a substring of length A from str1, convert it into an integer using int(), and subsequently add it to the result list. Once the loop concludes, we print the content of the result list as a string, resulting in the output message The resultant list: [1, 3, 5, 7, 9].

This code efficiently separates the string "13579" into its constituent digits and organizes them in a list, which is then displayed in the output message.

Conclusion

In this article, we looked at four different methods for splitting an integer into its component digits. We began by converting integers to strings and then back to integers using list comprehension and the str() and int() functions.

Following that, we provided a more mathematical technique that uses the math.ceil() and math.log() functions to avoid text translation. Next, we looked at a way to work with integers in string format that makes use of the map() and str.split() functions.

Lastly, we also demonstrated a loop-based method for splitting integers. You can easily manage and process integer values as individual digits in Python programs if you understand and utilize all these methods.

Vaibhhav Khetarpal avatar Vaibhhav Khetarpal avatar

Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.

LinkedIn