Implementing Integer to List in Python
In Python, you can convert a non-negative integer to a list of its digits using various techniques. Let's explore a few different approaches:
Using a While Loop
The most straightforward approach is to use a while
loop to repeatedly extract the last digit of the integer and append it to a list. Here's an example:
def int_to_list(num):
"""
Convert a non-negative integer to a list of its digits.
Args:
num (int): The non-negative integer to be converted.
Returns:
list: A list of the digits of the input integer.
"""
digits = []
while num > 0:
digit = num % 10
digits.append(digit)
num //= 10
return digits[::-1]
## Example usage
print(int_to_list(12345)) ## Output: [1, 2, 3, 4, 5]
In this implementation, the int_to_list()
function takes a non-negative integer as input and returns a list of its digits. The function uses a while
loop to repeatedly extract the last digit using the modulo operator (%
), append it to the digits
list, and then divide the integer by 10 to move to the next digit.
Using List Comprehension
Alternatively, you can use a more concise approach with Python's list comprehension feature:
def int_to_list(num):
"""
Convert a non-negative integer to a list of its digits.
Args:
num (int): The non-negative integer to be converted.
Returns:
list: A list of the digits of the input integer.
"""
return [int(digit) for digit in str(num)][::-1]
## Example usage
print(int_to_list(12345)) ## Output: [1, 2, 3, 4, 5]
In this implementation, the int_to_list()
function first converts the input integer to a string, then uses a list comprehension to iterate over the characters in the string, convert each character back to an integer, and append the digits to a list. Finally, the list is reversed to maintain the original order of the digits.
Using the map()
Function
You can also use the map()
function in combination with the list()
function to achieve the same result:
def int_to_list(num):
"""
Convert a non-negative integer to a list of its digits.
Args:
num (int): The non-negative integer to be converted.
Returns:
list: A list of the digits of the input integer.
"""
return list(map(int, str(num)))[::-1]
## Example usage
print(int_to_list(12345)) ## Output: [1, 2, 3, 4, 5]
In this implementation, the int_to_list()
function first converts the input integer to a string, then uses the map()
function to apply the int()
function to each character in the string, effectively converting them back to integers. The resulting map object is then converted to a list, and the list is reversed to maintain the original order of the digits.
All three approaches achieve the same result of converting a non-negative integer to a list of its digits. The choice of which method to use depends on your personal preference, the specific requirements of your project, and the readability and maintainability of the code.