Splitting a Number into Individual Digits Python

jabermudez11

Justin Bermudez

Posted on December 6, 2020

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.

💖 💪 🙅 🚩
jabermudez11
Justin Bermudez

Posted on December 6, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Learning Python
javascript Learning Python

November 28, 2024

Calculate savings with Python!
beginners Calculate savings with Python!

November 26, 2024

UV the game-changer package manager
programming UV the game-changer package manager

November 24, 2024

Beginners Guide for Classes
python Beginners Guide for Classes

November 20, 2024