The most robust and Pythonic way to split an integer into a list is to use a combination of str(), int(), and list comprehension.
The first step is to convert an input number into a string using the str() function, which makes it iterable. Then, use a list comprehension to iterate over each character and create a new list from it. When creating a new list, ensure that each character is converted back to an integer.
Here is the code:
new_int = 3456789 print(new_int) # Output: 3456789 # Using list comprehension to convert integer to list of digits digits = [int(i) for i in str(new_int)] print(digits) # Output: [3, 4, 5, 6, 7, 8, 9]
The time complexity is O(d), where d is the number of digits (log10(num) + 1).
What if the input is a negative number?
If you are working with a negative value, the best approach is to either take it as an absolute value, ignore the sign, or raise an error, depending on your requirements.
To calculate the absolute value of an input, always use the built-in abs() function.
def converting_digits_to_list(num): num = abs(num) # Handle negative return [int(digit) for digit in str(num)] print(converting_digits_to_list(-1921)) # Output: [1, 9, 2, 1]
Even if the number is negative, we still obtain a list of positive integers.
Non-Integer Inputs
If you pass a string or data other than a numeric value, it will throw a TypeError. To prevent it, we can use the built-in isintstance() method to check the input value’s type and create a condition based on it.
def converting_digits_to_list(num): if not isinstance(num, int): print("Input must be an integer") else: num = abs(num) # Handle negative print([int(digit) for digit in str(num)]) converting_digits_to_list("Krunal") # Output: Input must be an integer
Using map() with list()
First, you convert the integer to a string using the str() method and then use the map() function with the help of the int() function to iterate over each character in the string “3456789” and convert each character back into an integer.
Finally, wraps the map object in a list(), transforming it into a proper Python list.
new_int = 3456789 print(new_int) # Output: 3456789 digits = list(map(int, str(new_int))) print(digits) # Output: [3, 4, 5, 6, 7, 8, 9]
That’s all!