Reputation: 3
def sumList(arr):
items = len(arr)
if(items == 0):
return 0
elif(items == 1):
return arr[0]
else:
return(arr[0] + sumList(arr[1:]))
print(sumList([2, 4, 6, 10, 123]))
This code will still run if the "else if" part is commented out. But, shouldn't the last else
give an error for the last case when only one item is present as it's returning the list starting from index 1, which does not exist?
Upvotes: 0
Views: 58
Reputation: 41872
Let's clarify the question: you seem to be asking why this code:
def sumList(array):
items = len(array)
if items == 0:
return 0
if items == 1:
return array[0]
return array[0] + sumList(array[1:])
still works if/when we remove the second conditional expression:
def sumList(array):
items = len(array)
if items == 0:
return 0
#if items == 1:
# return array[0]
return array[0] + sumList(array[1:])
And the answer that @Tomothy32 provides tells us that the last line will eventually become:
return array[0] + sumList([])
Which due to your first conditional expression, becomes:
return array[0] + 0
In Python 3 we can express this as simply:
def sumList(array):
if not array: # empty containers are false in boolean context
return 0
head, *tail = array # Python 2: head, tail = array[0], array[1:]
return head + sumList(tail)
Upvotes: 0
Reputation: 16593
Slices will never give an index out-of-range error. For example:
mylist = [1, 2, 3]
print(mylist[10000:])
# []
Upvotes: 3