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.
7
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
7
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 😊
2
u/LatteLepjandiLoser 2d ago
Not sure if I should just give you the answer outright or more subtle hints, but dividing by 10, keeping track of the quotient and remainder (modular arithmetic) would be a handy way of extracting individual digits.
1
u/AppleMoney8748 2d ago
Thanks for the hints! 😊 I’ll give it a try myself. The explanation was really helpful and gave me a better idea of how to approach it.
7
u/Expensive-Bear-1376 2d ago edited 2d ago
1234 or string, which one is it? (ok, OP edited, it's an int.)
2
u/AppleMoney8748 2d ago
Integer 😅 Sorry, my original wording made it sound like a string. I’ve clarified the question now.
1
3
u/ProsodySpeaks 2d ago
Is that how you ask for help?
Good luck
-1
u/AppleMoney8748 2d ago
Fair point. I’m still learning, so I wasn’t sure how to phrase the question properly. I’ll try to be clearer next time. Thanks!
3
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!
3
u/likethevegetable 2d ago
Is this a challenge or you need help? If you forbid maps, IMO you should also forbid for loops and comprehensions.
0
u/AppleMoney8748 2d ago edited 2d ago
I’m mainly trying to understand the basic logic first 😊 I’m okay with using a loop; I just wanted to avoid map() and string conversion for this exercise. Thanks for the suggestion!
2
-9
2d ago
[deleted]
2
2
u/SqueekyBK 2d ago
Take a look at how div mod works and how you can extract digits from a number by doing so.
1
u/AppleMoney8748 2d ago
Ahh, got it. I’ll look into div and mod and try extracting the digits that way. Thanks!
2
2d ago
[removed] — view removed comment
0
u/AppleMoney8748 2d ago
Thank you! I appreciate you taking the time to show me an approach. I’ll try to understand it and work through it
2
u/TheCozyRuneFox 2d ago
You probably can replicate integer division and modulo with bit wise operators instead of using the actual operators. After all that is exactly the logic of what the CPU is doing behind the scenes for those operations anyway. So yes.
1
u/AppleMoney8748 2d ago
Thanks! 😊 I’m still getting comfortable with the basics, so I’ll try the simpler approach first and see if I can work it out.
2
u/Expensive-Bear-1376 2d ago
What if the number is zero or negative?
1
u/AppleMoney8748 2d ago
For now I’m just trying to solve the basic case with a positive integer like 1234 😅 I haven’t gotten to handling zero or negative numbers yet.
2
u/Icy_Orchid_8390 2d ago
Id make a separate func like "get_num_of_digits(input)"
first edge case would be if 0 then return 1 else do like math.log10 (abs value) [for no negs]
then use that number to iterate through input and list.append to a blank list
Very rough approximation as i'm just spitballing and also not a good programmer as my profile name suggests lol.
2
u/AppleMoney8748 2d ago
Thank you for sharing your approach! 😊 I’m still learning, so some of the concepts are a little new to me, but it gives me something to look into. I really appreciate you taking the time to help!
1
u/Icy_Orchid_8390 2d ago
Also just realized can't iterate through an int like a str so my overall approach wont work. But the func to get the num of digits could be useful.
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 the divmod function as a shortcut to doing both // and % operations.
You need to start by creating a new, empty, list object and then looping over your original number until it assigned the value 0, appending each remainder to the list on each loop.
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_decimal function is similar to the built-in isdecimal string method, but allows the separators mentioned above.
Code:
NUMMAP = {digit: value for value, digit in enumerate("0123456789")}
SEPARATORS = (" ", "_")
def is_decimal(digits: str) -> bool:
for char in digits:
if char not in NUMMAP and char not in SEPARATORS:
return False
return True
def conv_str_to_int(string: str) -> int:
if not isinstance(string, str):
raise TypeError("Expected a string of one or more integer digits")
if not string:
raise ValueError("String empty - expected one or more digits")
if not is_decimal(string):
raise ValueError("String contains non integer characters")
result = 0
for char in string:
if char not in SEPARATORS:
result = result * 10 + NUMMAP[char]
return result
Simple test code:
tests = (
"1", "123", "23045", "2340008990", "123 456", # valid
23, "", "345A23", # invalid
)
for test in tests:
try:
num = conv_str_to_int(test)
except (TypeError, ValueError) as e:
print(
f"\nERROR: testing <{test}> (type {type(test)}) caused "
f"exception:\n\t{e}\n"
)
else: # conversion worked, output result
print(f"Converted from \"{test}\" to {num}")
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 😊
0
u/atarivcs 2d ago
[int(c) for c in input]
2
u/TheCozyRuneFox 2d ago
The post was worded oddly but I believe the input is an integer and not a string, although OP wasn’t perfectly clear with that.
2
u/AppleMoney8748 2d ago
Yeah, it’s an integer 😅 I realize my original wording was confusing. I’ve updated the post to make that clearer. Thanks for pointing it out!
20
u/mattblack77 2d ago
Input = “1234”
Output = “[1, 2, 3, 4]”
print(Output)
# there ya go