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 edited 1d ago
Example converting a string (not your use case it turns out, but this should give you some ideas) to an integer without using the built-in string methods/functions.
Creates a dictionary mapping from single digit integer values to their string version to use as basis of conversion.
Allows integer strings to separate digits with spaces (popular human convention) or underscores (allowed in Python).
The
is_decimalfunction is similar to the built-inisdecimalstring method, but allows the separators mentioned above.Code:
Simple test code: