Python递归求长度代码疑问:return 1+length(list1[1:])解析
Let's walk through this recursive function line by line to clear up your confusion—recursion can feel counterintuitive at first, but tracing through actual calls makes it much easier to grasp.
First, here's the original code for reference:
def length(list1): if list1 == [] or list1 == "": return 0 else: return 1 + length(list1[1:])
Why do we add 1?
The 1 represents the current element we're counting right now. Recursion works by breaking a problem into smaller versions of itself:
- When you call
length([1,2,3,4,5]), you're saying "the total length is 1 (for the first element1) plus the length of the rest of the list ([2,3,4,5])". - Each subsequent call does the same: counts the first element of its input list as
1, then asks the function to calculate the length of the remaining elements. - When we hit an empty list (the base case), we return
0because there are no elements left to count.
Let's trace this with your example [1,2,3,4,5]:
length([1,2,3,4,5])→1 + length([2,3,4,5])length([2,3,4,5])→1 + length([3,4,5])length([3,4,5])→1 + length([4,5])length([4,5])→1 + length([5])length([5])→1 + length([])length([])→ returns0
Now we backtrack to calculate the total: 1+1+1+1+1+0 = 5—which matches the expected result.
Why use list1[1:] instead of starting at 0?
list1[1:] creates a new list that excludes the first element, which is how we shrink the problem size with each recursive call. If we used list1[0:] instead:
list1[0:]returns the entire original list (it's the same as justlist1).- This means every recursive call would pass the exact same list, never getting closer to the empty list base case.
- The function would keep calling itself infinitely until Python hits its recursion depth limit.
Why does list1[0:] cause the function to fail?
As mentioned above, using list1[0:] leads to infinite recursion. Python has a default maximum recursion depth (usually around 1000 calls) to prevent the program from crashing entirely. When you exceed this limit, Python raises a RecursionError because it can't keep track of all the pending function calls anymore.
The key takeaway with recursion is always making sure your recursive calls move toward a base case—here, that means reducing the input list each time by removing one element.
内容的提问来源于stack exchange,提问作者user9654395

