Skip to main content

How to Split Integers into Digits in Python

This guide explores various methods to split an integer into its individual digits in Python. We'll cover techniques using string conversion, the map() function, mathematical operations, and the divmod() function, providing a comprehensive toolkit for this common task.

Splitting Integers with String Conversion and List Comprehension

The most common approach is to convert the integer to a string and then use a list comprehension to convert each character back to an integer.

an_int = 13579
list_of_digits = [int(x) for x in str(an_int)]
print(list_of_digits) # Output: [1, 3, 5, 7, 9]
  • The integer is converted to a string with str(an_int).
  • The list comprehension then iterates through every character and uses the int() constructor to convert it back to a number.

Splitting Integers with a for Loop

You can use a for loop as an alternative to list comprehensions:

an_int = 13579
list_of_digits = []
for x in str(an_int):
list_of_digits.append(int(x))
print(list_of_digits) # Output: [1, 3, 5, 7, 9]
  • This approach is more verbose, and has the same result as using the list comprehension from above.

Splitting Integers with map()

You can also use the map() function to iterate over the string representation of the integer.

an_int = 13579
list_of_digits = list(map(int, str(an_int)))
print(list_of_digits) # Output: [1, 3, 5, 7, 9]
  • The map() applies the int() function to each character in the string and returns a map object.
  • Then you can convert this map object to a list using list().

Splitting Integers with Mathematical Operations

To avoid string conversions, you can use mathematical operations to extract the digits. This approach works from right to left.

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)) # Output: [1, 2, 3, 4, 5]
print(split_integer(100)) # Output: [1, 0, 0]

This approach is not easy to understand because of the mathematical operations that involve the logarithm. This code calculates the digits without converting them to string.

Splitting Integers with divmod()

To split an integer into digits from right to left, you can use divmod().

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) # Output: [9, 7, 5, 3, 1]
  • divmod(an_int, 10) will return the reminder of the division and the value of the operation an_int // 10, truncating the value at each step, working from right to left.
  • If you require to get the result from left to right, use the reverse() method or list slicing with [::-1].