Split integer into digits python recursion

How would you split up the number 123456789 into [1,2,3,4,5,6,7,8,9] using Python?

Alex Riley

157k44 gold badges249 silver badges229 bronze badges

asked Jan 20, 2015 at 23:10

0

One way is to turn the number into a string first and then map each character digit back to an integer:

>>> map[int, str[123456789]]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

This does the following:

  • str turns the integer into a string: '123456789'

  • map applies the function int to each character in this string in turn, turning each one back into an integer value.

  • a list of these integers is returned.

answered Jan 20, 2015 at 23:14

Alex RileyAlex Riley

157k44 gold badges249 silver badges229 bronze badges

7

You can convert the number into a string and then do a list comprehension -

>>>[int[digit] for digit in str[123456789]]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

answered Jan 20, 2015 at 23:18

You can also do this without turning your number into a string like so:

def splitNum[n]:
    if n < 10
        return [n]
    else:
        return splitNum[n // 10] + [n % 10]

This method uses recursion, but you can also do this without recursion

def splitNum[n]:
    digits = []
    while n > 0:
        digits.insert[0, n % 10] # add ones digit to front of digits
        n = n // 10
    return digits

Both use the following facts:

  • x // 10, because of integer division, "chops off" the ones digit, ie 1234 // 10 is 123
  • x % 10 is that ones digit, ie 1234 % 10 is 4

answered Jan 20, 2015 at 23:23

JJW5432JJW5432

6978 silver badges15 bronze badges

2

Use the inbuilt list function in Python in the following way:

a = 123456789
p = str[a]
li = list[p]
s = []
for e in li:
    a = int[e]
    s.append[a]
print s    

From the documentation:

list[iterable] -> new list initialized from iterable's items

EDIT:

Since the list[] method returns a list containing only string elements, I have created an empty list s, and have then used a for loop to iterate through each string element, converted each of those elements to integer, and have then appended those elements inside the empty list s.

answered Jan 20, 2015 at 23:21

Manas ChaturvediManas Chaturvedi

4,83018 gold badges51 silver badges102 bronze badges

1

  1. HowTo
  2. Python How-To's
  3. Split Integer Into Digits in Python

Created: May-26, 2021

  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

This tutorial will discuss different methods to split an integer into digits in Python.

Use List Comprehension to Split an Integer Into Digits in Python

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

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]

The number num is first converted into a string using str[] in the above code. Then, list comprehension is used, which breaks the string into discrete digits. Finally, the digits are converted back to an integer using the int[] function.

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 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. 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.

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]

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, separator, and the maxsplit.

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

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]

Here, we used the str.split[] method to split the given number in string format into a list of strings containing every number. Then the map[] function is used, which is utilized to generate a map object which converts each string into an integer. Finally, list[mapping] is used to create a list from the map object.

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+slice to split an integer into digits in Python.

str1 = '13579'
# initializing substring
A = 1
# create a result list
result = []
for i in range[0, len[str1], A]:
    # convert to int, after the slicing process
    result.append[int[str1[i : i + A]]]
  
print["The resultant list : " + str[result]]

Output:

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

Related Article - Python Integer

  • Convert Int to Binary in Python
  • Integer Programming in Python
  • Convert Boolean Values to Integer in Python
  • Convert String to Integer in Python

    Related Article - Python String

  • Convert Int to Binary in Python
  • Integer Programming in Python
  • Convert Boolean Values to Integer in Python
  • Convert String to Integer in Python
  • How do you split an integer into digits in Python?

    To split an integer into digits: Use the str[] class to convert the integer to a string. Use a list comprehension to iterate over the string. On each iteration, use the int[] class to convert each substring to an integer.

    How do I split an int into its digits?

    A simple answer to this question can be:.
    Read A Number "n" From The User..
    Using While Loop Make Sure Its Not Zero..
    Take modulus 10 Of The Number "n".. This Will Give You Its Last Digit..
    Then Divide The Number "n" By 10.. ... .
    Display Out The Number..

    How do you convert a number to a digit in Python?

    This can be done quite easily if you: Use str to convert the number into a string so that you can iterate over it. Use a list comprehension to split the string into individual digits. Use int to convert the digits back into integers.

    How do you split a number array in Python?

    Splitting NumPy Arrays Joining merges multiple arrays into one and Splitting breaks one array into multiple. We use array_split[] for splitting arrays, we pass it the array we want to split and the number of splits.

    Chủ Đề