How to Split an Integer into Digits in Python?

How to Split an Integer into Digits in Python?

  • Python
  • 2 mins read

This tutorial shows, how to split an integer into digits in Python.

To split an integer into digits, use the following formula:

  1. To convert an integer to a string, use the str() method.
  2. Iterate over the string using a list comprehension.
  3. Use the int() method to convert each substring to an integer on each iteration.

Split an Integer Using List in Python

my_int = 25876

my_list = [int(x) for x in str(my_int)]

print(my_list)  # [2, 5, 8, 7, 6]

We used the str() method to convert the integer to a string so that we could iterate over it.

The following step is to iterate over the string using a list comprehension.

List comprehensions are used to perform an operation on each element or to select a subset of elements that satisfy a condition.

We pass the string to the int() method on each iteration to convert it to an integer.

Split an Integer into String Using For Loop in Python

To achieve the same result, you can also use a simple for loop.

To split an integer into digits, use the following formula:

  1. To convert an integer to a string, use the str() method.
  2. To iterate over the string, use a for loop.
  3. Convert each substring to an integer and append it to a list using the int() method.
my_int = 25876

my_list = []

for x in str(my_int):
    my_list.append(int(x))

print(my_list) # [2, 5, 8, 7, 6]

We iterate over the digits wrapped in a string, using the int() method to convert the value to an integer before appending the result to a list.

Split an Integer into String Using Map Function

You can also use the map() function to divide an integer into digits.

my_int = 25876

my_list = list(map(int, str(my_int)))

print(my_list)  # [2, 5, 8, 7, 6]

The map() function takes two arguments: a function and an iterable, and it calls the function with each item in the iterable.

Because strings can be iterated while integers cannot, the first step is to convert the integer to a string.

Each substring from the string is passed to the int() method, which converts the values to integers.

Please note that the map() function returns a map object rather than a list, we must use the list() class to convert the map object to a list.