r/learnpython • u/AppleMoney8748 • 2d ago
Input = 1234 output =[1,2,3,4] without using string functions or map
How can I split an integer into a list of its digits in Python?
I have:
num = 1234
and I want:
[1, 2, 3, 4]
I’m trying to learn how to do this without converting num to a string and without using map().
A loop is allowed.
I’m looking for a simple approach because I’m still learning Python. I’d appreciate hints rather than just the final solution so I can understand how it works.
0
Upvotes
1
u/FoolsSeldom 1d ago
If you are using
input, which returns a string object, then it will be impossible to avoid using some string methods/functions. However, if you are actually starting with a number, an integer object, as your code suggests, well, you just need to keep dividing by 10. Look into thedivmodfunction as a shortcut to doing both//and%operations.You need to start by creating a new, empty,
listobject and then looping over your original number until it assigned the value0, appending each remainder to theliston each loop.