DEV Community

Justin Bermudez
Justin Bermudez

Posted on

15 2

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)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay