DEV Community

Justin Bermudez
Justin Bermudez

Posted on

Splitting a Number into Individual Digits Python

If you are looking only for the code then here it is

number = 12345
numList = [int(digit) for digit in str(number)]
Enter fullscreen mode Exit fullscreen mode

numList in this example would return
[1, 2, 3, 4, 5]

The best way to look at all the individual numbers in a number is to use list comprehension by first turning the number into a string. This way you will be able to iterate over the string as each individual character. Then finally turn the individual characters into a number. This can all be done in side of a list.

To breakdown the above code, to make it look nicer:

for digit in str(number):
    int(digit)
Enter fullscreen mode Exit fullscreen mode

This block of code returns a number, so if you put it around square brackets, then it will become a list.
Then you would be able to iterate over the list and do as you please.

Top comments (0)