Easily Ways To Split An Integer Into Digits in Python

Split an integer into digits in Python

This article will show you how to split an integer into digits in Python, which is probably one of the most commonly used operations in practice when working with Python. Let’s continue below to know more.

How to split an integer into digits in Python?

Here we will guide you through four ways to solve the above problem.

Using for loop and append() function

You can learn more about the for loop syntax here.

list.append() syntax:

list.append(element)

Parameters:

  • element: an element that we want to add to the list.

First, we’ll cast a number to a string that can iterate over each element. Then we’ll iterate over each element by using the for loop, cast each to an int, and insert it into an empty list we’ve created. Like this:

year = 2022
digits = []

for digit in str(year):
  digits.append(int(digit))

print(digits)

Output:

[2, 0, 2, 2]

Using list comprehension

You can learn more about the list comprehension syntax here.

This way has the same idea as the one above, but in this way, we will write it more concisely than the above method. Like this:

year = 2022
digits = [int(digit) for digit in str(year)]

print(digits)

Output:

[2, 0, 2, 2]

Using map() function

You can learn more about the map() syntax here.

The map() function will apply the specific function to all elements of an iterable. Based on that, we will apply the int function to turn all the characters of a number into integers and convert them to a list using the list() function. Like this:

year = 2022
digits = map(int, str(year))
digits = list(digits)

print(digits)

Output:

[2, 0, 2, 2]

Using recursion

A function that calls itself in its own function definition is called recursion. Recursion is used to solve repetitive problems.

In this case, we use recursion to create a function that continuously divides by 10 and gets the remainder by adding the remainder to a list on each return.

Look closely at the example below to better understand recursion.

year = 2022

def split_number(n):  
  # Escape recursion
  if n < 10:
    return [n]

  # Use recursion
  return split_number(n // 10) + [n % 10]

# Explain:
# 2022 -> split_number(202) + [2]
# 202  -> split_number(20)  + [2]
# 20   -> split_number(2)   + [0]
# 2    ->                     [2]

print(split_number(year))

Output:

[2, 0, 2, 2]

Notice: If you’re a beginner, we don’t recommend doing it this way!

Summary

Through the article, we have introduced four ways to split an integer into digits in Python. We hope the article will be helpful to you in your learning process.

Have a lucky day!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *