Split an integer into digits in Python

avatar

Borislav Hadzhiev

Last updated: Jun 25, 2022

banner

Photo from Unsplash

Split an integer into digits in Python #

To split an integer into digits:

  1. Use the str() class to convert the integer to a string.
  2. Use a list comprehension to iterate over the string.
  3. On each iteration, use the int() class to convert each substring to an integer.
main.py
my_int = 13579 my_list = [int(x) for x in str(my_int)] print(my_list) # 👉️ [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.

To split an integer into digits:

  1. Use the str() class to convert the integer to a string.
  2. Use a for loop to iterate over the string.
  3. Use the int() class to convert each substring to an integer and append them to a list.
main.py
my_int = 13579 my_list = [] for x in str(my_int): my_list.append(int(x)) print(my_list) # 👉️ [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.

main.py
my_int = 13579 my_list = list(map(int, str(my_int))) print(my_list) # 👉️ [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.

Strings are iterable and integers are not, so the first step is to convert the integer to a string.

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.