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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.