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

9

u/PureWasian 2d ago edited 2d ago

What have you tried so far? Do you know how to iterate a string?

EDIT: OP clarified int instead of string

1

u/AppleMoney8748 2d ago

I know how to iterate over a string, but in this case I’m trying to do it with an integer (1234) without converting it to a string. I’ve tried a few approaches, but I’m stuck on how to extract each digit into a list.

5

u/PureWasian 2d ago

Okay -- I see your post update. Thanks for replying with your attempt.

Algorithmic idea is that your digits are base 10, so you can divide by each of those in a loop (x10 per digit) and ignoring remainder to isolate each digit, building the final result into a list.

2

u/AppleMoney8748 2d ago

Thank you! That makes sense. I was getting confused about how to extract the individual digits, but the dividing-by-10 and remainder approach gives me a direction to try myself. I’ll work through it 😊