Jan Egbers Jan Egbers - 1 year ago 88
Python Question

Add first and last number of a list

while learning Python at pyschools, I got stuck at question 2.13.
I am asked to add the first and last numbers in a list. This is what I came up with:

def addFirstAndLast(x):
return x[0] + x[-1]

But when I run the code, i get an error that says:"IndexError: list index out of range". I can't find the problem though and when I searched for this question, the answers were equal to my code.

Maybe it has to do with the test cases:

1. addFirstAndLast([2])

2. addFirstAndLast([2, 2, 3])

3. addFirstAndLast([])

Can you help me please?

Answer Source

You need to check if your list is empty or not.

def addFirstAndLast(x): 
    return (x[0] + x[-1]) if x else 0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download