1

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)

developer_hatch
  • 15,898
  • 3
  • 42
  • 75
Saykat
  • 124
  • 2
  • 12

4 Answers4

1

Try this:

[int(i) for i in str(504)]

Output:

[5,0,4]
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
Yogesh Nikam Patil
  • 1,192
  • 13
  • 18
1

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]
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

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)
developer_hatch
  • 15,898
  • 3
  • 42
  • 75
0

You may try this:

n = 504
lst = list(map(int,str(n)))
print(lst)

Output:

[5,0,4]
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52