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 codes doing it. Hence having ways to perform this task using shorthands comes handy. Let’s discuss ways in which this can be performed.
Method #1 : Using list comprehension
List comprehension can be used as a shorthand to the longer format of naive method. In this method, we convert the number to string and then extract its each character and re convert it to integer.
# Python3 code to demonstrate # conversion of number to list of integers # using list comprehension # initializing number num = 2019 # printing number print ("The original number is " + str(num)) # using list comprehension # to convert number to list of integers res = [int(x) for x in str(num)] # printing result 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 number to the desired integer value to be reconverted to the list format.
# Python3 code to demonstrate # conversion of number to list of integers # using map() # initializing number num = 2019 # printing number print ("The original number is " + str(num)) # using map() # to convert number to list of integers res = list(map(int, str(num))) # printing result print ("The list from number is " + str(res)) |
Output:
The original number is 2019 The list from number is [2, 0, 1, 9]
Recommended Posts:
- Python | Convert list of numerical string to list of Integers
- Python | Convert a list of multiple integers into a single integer
- Python | Convert list of string into sorted list of integer
- Python | Convert list of tuples to list of list
- Python | Convert list of string to list of list
- Python | Convert list of strings to list of tuples
- Python | Convert 1D list to 2D list of variable length
- Python | Convert string enclosed list to list
- Python | Convert a string representation of list into list
- Python | Convert list of tuples to list of strings
- Python | Convert a nested list into a flat list
- Python | Convert list of tuples into list
- Python | Convert given list into nested list
- Python | Convert list into list of lists
- Python | Converting all strings in list to integers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



