Python | Convert number to list of integers
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
It can 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
# Python3 code to demonstrate# conversion of number to list of integers# using list comprehension# initializing numbernum = 2019# printing numberprint("The original number is " + str(num))# using list comprehension# to convert number to list of integersres = [int(x) for x in str(num)]# printing resultprint("The list from number is " + str(res)) |
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
# Python3 code to demonstrate# conversion of number to list of integers# using map()# initializing numbernum = 2019# printing numberprint("The original number is " + str(num))# using map()# to convert number to list of integersres = list(map(int, str(num)))# printing resultprint("The list from number is " + str(res)) |
The original number is 2019 The list from number is [2, 0, 1, 9]
Method #3: Using enumerate function
Python3
n=2019res = [int(x) for a,x in enumerate(str(n))]print(res) |
[2, 0, 1, 9]
Method: Using lambda function
Python3
n=2019x=list(filter(lambda i:(i),str(2019)))print(x) |
['2', '0', '1', '9']
Method : Using divmod
One additional approach to convert a number to a list of integers is to use the divmod function to repeatedly divide the number by 10 and get the remainder. This can be done in a loop until the number becomes 0. The remainders can be added to a list, which can then be reversed to get the list of integers in the correct order.
Here is an example of how this can be done:
Python3
# Python3 code to demonstrate# conversion of number to list of integers# using divmod and a loop# initializing numbernum = 2019# printing numberprint("The original number is " + str(num))# using divmod and a loop# to convert number to list of integersres = []while num > 0: num, remainder = divmod(num, 10) res.insert(0,remainder)# printing resultprint("The list from number is " + str(res))#This code is contributed by Edula Vinay Kumar Reddy |
The original number is 2019 The list from number is [2, 0, 1, 9]



.gif)

Please Login to comment...