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
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
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
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]