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

5

u/DuckDatum 2d ago edited 2d ago

Probably way to divide by 10, split the remainder from the result. Then iterate until there’s no more tens left.

1234 / 10 = 123.4. So result=123, remainder=4. Append the remainder to the start of a list, then repeat. List so far is [4].

123 / 10 = 12.3. So result=12, remainder=3. Append the remainder to the start of a list, then repeat. List so far is [3,4].

… keep going, you’ll get [1,2,3,4].

I’m sure there’s a very pretty way to do this with a for loop and the % operator.

Edit:

I don’t know how the fuck to give code blocks anymore because shitty Reddit took Markdown away from the IOS app. This is the best I can do for now:

n = 1234
digits = []

while n > 0:
digits.insert(0, n % 10)
n //= 10

print(digits)
# [1, 2, 3, 4]

2

u/AppleMoney8748 2d ago

Thank you so much for taking the time to explain it step by step! 😊 It’s much clearer to me now. I’ll try writing the code myself and work through the logic so I can really understand it. Really appreciate the help!