0
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?

1
  • Do you mean that the code still run when when the elif part is commented ? Commented Mar 5, 2019 at 7:36

2 Answers 2

3

Slices will never give an index out-of-range error. For example:

mylist = [1, 2, 3]
print(mylist[10000:])
# []
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.