0

How do I convert an int into a list of its digits for eg.

a = 1234

I have to use it as

[1,2,3,4]

I have tried using

list(a)

But it shows an error.Anything else that I could use

saurabh
  • 293
  • 2
  • 7
  • 19

1 Answers1

8

You can convert a to a string first:

In [106]: map(int, str(a)) #in python3, you need list(map(int, str(a)))
Out[106]: [1, 2, 3, 4]

Or use list comprehension instead of map:

In [108]: [int(digit) for digit in str(a)]
Out[108]: [1, 2, 3, 4]

Or a manual approach:

In [10]: def bar(num):
    ...:     res=[]
    ...:     while num>0:
    ...:         res.append(num%10)
    ...:         num//=10
    ...:     return res[::-1]

In [11]: bar(1234567890)
Out[11]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

All the three ways runs equally in time:

In [24]: def foo(num):
    ...:     return list(map(int, str(num)))

In [25]: def bar(num):
    ...:     res=[]
    ...:     while num>0:
    ...:         res.append(num%10)  #or try divmod(n, 10) if you like builtins
    ...:         num//=10
    ...:     return res[::-1]

In [26]: def lstcomp(num):
    ...:     return [int(digit) for digit in str(num)]

In [27]: num=1234567890123456789012345678901234567890

In [28]: timeit foo(num)
100000 loops, best of 3: 13.1 µs per loop

In [29]: timeit bar(num)
100000 loops, best of 3: 15.7 µs per loop

In [30]: timeit lstcomp(num)
100000 loops, best of 3: 14.6 µs per loop

EDIT:

You can also generate a tuple represented "linked list" as @J.F.Sebastian mentioned:

In [523]: f = lambda n, ll=None: f(n//10, (n%10, ll)) if n else ll

In [524]: f(123)
Out[524]: (1, (2, (3, None)))

which could be converted to an ordinary list in O(n) time:

In [537]: llst=f(123)
     ...: res=[]
     ...: while llst:
     ...:     res.append(llst[0])
     ...:     llst=llst[1]
     ...: print res
[1, 2, 3]
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
  • I have use that already I just wanted to know that is there anything directly that I could use as it is in python that ints are not iterable but strings are so any other that that could change this format directly – saurabh Mar 02 '14 at 12:24
  • @saurabh I don't think there is one builtin method doing this, since as you mentioned an int is not an iterable. You can make it a function if you want to reuse it. – zhangxaochen Mar 02 '14 at 12:30
  • More traditional *functional* approach avoids a mutable state e.g., `f = lambda n, ll=None: f(n//10, (n%10, ll)) if n else ll` btw, `map(int, str(a))` is more functional than `bar()` – jfs Mar 02 '14 at 18:01
  • @J.F.Sebastian `f(12)` returns `(1, (2, None))` with your demo – zhangxaochen Mar 03 '14 at 02:44
  • @zhangxaochen: it is an expected result (a linked list represented using tuples). It could be converted to an ordinary Python list in `O(n)`. – jfs Mar 03 '14 at 02:46
  • @J.F.Sebastian edited in my answer ;) – zhangxaochen Mar 03 '14 at 02:55