Number to list of digits python

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    The interconversion of data types is a problem that is quite common in programming. Sometimes we need to convert a single number to list of integers and we don’t wish to spend several lines of code doing it. Hence having ways to perform this task using shorthands comes in handy. Let’s discuss ways in which this can be performed. 

    Method #1: Using list comprehension

    Itcan be used as a shorthand for the longer format of the naive method. In this method, we convert the number to a string and then extract each character and re-convert it to an integer. 

    Python3

    num = 2019

    print("The original number is " + str(num))

    res = [int(x) for x in str(num)]

    print("The list from number is " + str(res))

    Output

    The original number is 2019
    The list from number is [2, 0, 1, 9]

    Method #2: Using map() map function can be used to perform the following task converting each of the string converted numbers to the desired integer value to be reconverted to the list format. 

    Python3

    num = 2019

    print("The original number is " + str(num))

    res = list(map(int, str(num)))

    print("The list from number is " + str(res))

    Output

    The original number is 2019
    The list from number is [2, 0, 1, 9]

    Method #3: Using enumerate function

    Python3

    n=2019

    res = [int(x) for a,x in enumerate(str(n))]

    print(res)

    Method: Using lambda function

    Python3

    n=2019

    x=list(filter(lambda i:(i),str(2019)))

    print(x)

    Output

    ['2', '0', '1', '9']


    Here's a way to do it without turning it into a string first (based on some rudimentary benchmarking, this is about twice as fast as stringifying n first):

    >>> n = 43365644
    >>> [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10))-1, -1, -1)]
    [4, 3, 3, 6, 5, 6, 4, 4]
    

    Updating this after many years in response to comments of this not working for powers of 10:

    [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][bool(math.log(n,10)%1):]
    

    The issue is that with powers of 10 (and ONLY with these), an extra step is required. ---So we use the remainder in the log_10 to determine whether to remove the leading 0--- We can't exactly use this because floating-point math errors cause this to fail for some powers of 10. So I've decided to cross the unholy river into sin and call upon regex.

    In [32]: n = 43
    
    In [33]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
    Out[33]: [4, 3]
    
    In [34]: n = 1000
    
    In [35]: [(n//(10**i))%10 for i in range(math.ceil(math.log(n, 10)), -1, -1)][not(re.match('10*', str(n))):]
    Out[35]: [1, 0, 0, 0]
    

    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
  • Number to list of digits python

    How do you create a list of the digits of a number in Python?

    “how to make a list of digits of a number in python” Code Answer's.
    n = 1234..
    # convert integer to list of digits..
    list_of_digits = list(map(int, f"{n}")).
    # convert list of digits back to number..
    number = int(''. join(map(str, list_of_digits))).

    How do you isolate digits in Python?

    Making use of isdigit() function to extract digits from a Python string. Python provides us with string. isdigit() to check for the presence of digits in a string. Python isdigit() function returns True if the input string contains digit characters in it.

    How do I convert a value to a list in Python?

    Typecasting to list can be done by simply using list(set_name) . Using sorted() function will convert the set into list in a defined order. The only drawback of this method is that the elements of the set need to be sortable.

    How do you split an integer into a list in Python?

    split() functions to split an integer into digits in Python. 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.