Suppose I have integer
n = 504
I want it to be a list like this
ls = [5, 0, 4]
How can I approach? Here is my solution:
n = 504
tmpList = list(str(n))
ls = [int(i) for i in tmpList]
Any better way to do it?(probably a shorter way)
Suppose I have integer
n = 504
I want it to be a list like this
ls = [5, 0, 4]
How can I approach? Here is my solution:
n = 504
tmpList = list(str(n))
ls = [int(i) for i in tmpList]
Any better way to do it?(probably a shorter way)
Try this:
[int(i) for i in str(504)]
Output:
[5,0,4]
Perhaps a bit overkill, but you could use re.findall
here:
n = 504
parts = re.findall(r'\d', str(n))
print(parts)
['5', '0', '4']
Use map
if you want a list of actual integers:
parts = results = map(int, parts)
print(parts)
[5, 0, 4]
With a while loop it could be:
num = 504
result = []
while num > 10:
mod = num % 10
num = num // 10
result = [mod] + result
result = [num] + result
print(result)
You may try this:
n = 504
lst = list(map(int,str(n)))
print(lst)
Output:
[5,0,4]