How to Reverse a Number into a List Using Recursion in Python
This article explains how to transform a number like 1234 into a reversed list of its digits using both a straightforward string method and two recursive implementations—standard and tail recursion—while noting Python's general preference for iterative solutions.
Question: Convert a number into a reversed list of its digits, e.g., 1234 → [4,3,2,1], using recursion.
Simple method: cast the integer to a string, reverse it, and convert each character back to an integer.
Standard recursion
def reverse_order_list1(lst:list, tmp=[]):
if len(lst) == 0:
return tmp
num = lst.pop()
tmp.append(int(num))
return reverse_order_list1(lst, tmp=tmp)
print(reverse_order_list1(list(str(1234))))Tail recursion
def reverse_order_list2(lst:list, tmp=[]):
if len(lst) > 0:
num = lst.pop()
tmp.append(int(num))
reverse_order_list2(lst, tmp=tmp)
return tmp
print(reverse_order_list2(list(str(1234))))Note: In Python, recursion is generally discouraged for such tasks because loops are more efficient, but recursion can be convenient in certain scenarios.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
