Alex Rivera | Logout

Converting integer to digit list

Asked 2012-12-16T22:06:02.647
74

What is the quickest and cleanest way to convert an integer into a list?

For example, change 132 into [1,3,2] and 23 into [2,3]. I have a variable which is an int, and I want to be able to compare the individual digits so I thought making it into a list would be best, since I can just do int(number[0]), int(number[1]) to easily convert the list element back into int for digit operations.

Edit
Report

1 Answer

105

Convert the integer to string first, and then use map to apply int on it:

>>> num = 132
>>> map(int, str(num))    #note, This will return a map object in python 3.
[1, 3, 2]

or using a list comprehension:

>>> [int(x) for x in str(num)]
[1, 3, 2]
answered 2012-12-16T22:07:10.963

Your Answer