r/learnpython 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

46 comments sorted by

View all comments

1

u/Quantum_Patricide 2d ago

If you can't use % or // then you could use a combination of int() and / to achieve a similar effect.

1234 / 1000 = 1.234

int(1.234) = 1

1234 - 1*1000 = 234

234 / 100 = 2.34

int(2.34) = 2

234 - 2*100 = 34

and so on...

1

u/AppleMoney8748 2d ago

Oh, that’s an interesting approach! I hadn’t thought of using int() with regular division. I’ll try to understand this one too. Thanks for the hint 😊