# Convert a number to a list of integers

Posted on

### Question :

Convert a number to a list of integers

How do I write the `magic` function below?

``````>>> num = 123
>>> lst = magic(num)
>>>
>>> print lst, type(lst)
[1, 2, 3], <type 'list'>
``````

``````a = 123456
b = str(a)
c = []

for digit in b:
c.append (int(digit))

print c
``````

You mean this?

``````num = 1234
lst = [int(i) for i in str(num)]
``````

You could do this:

``````>>> num = 123
>>> lst = map(int, str(num))
>>> lst, type(lst)
([1, 2, 3], <type 'list'>)
``````

``````magic = lambda num: map(int, str(num))
``````

then just do

``````magic(12345)
``````

or

``````magic(someInt) #or whatever
``````

``````>>> from collections import deque
>>> def magic(num):
digits = deque()
while True:
num,r = divmod(num,10)
digits.appendleft(r)
if num == 0:
break
return list(digits)

>>> magic(123)
[1, 2, 3]
``````

According to my timings, this solution is considerably faster than the string method (`magic2`), even for smaller examples.

``````>>> def magic2(num):
return [int(i) for i in str(num)]
``````

Timings:

`magic`

``````>>> timeit.timeit(setup='from __main__ import magic', stmt='magic(123)')
1.3874572762508706
>>> timeit.timeit(setup='from __main__ import magic', stmt='magic(999999999)')
3.2624468999981673
``````

`magic2`

``````>>> timeit.timeit(setup='from __main__ import magic2', stmt='magic2(123)')
3.693756106896217
>>> timeit.timeit(setup='from __main__ import magic2', stmt='magic2(999999999)')
10.485281719412114
``````

Don’t use the word list as variable name! It is a name of python built in data type.

Also, please clarify your question. If you are looking for a way to create a one-member list, do the following:

``````a = 123
my_list = [a]
``````

``````a = 123
my_list = [int(d) for d in str(a)]
``````

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

``````def magic(x):