Jan Egbers
Jan Egbers

Reputation: 37

Add first and last number of a list

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?

Upvotes: 1

Views: 3089

Answers (5)

Sebastian Nielsen
Sebastian Nielsen

Reputation: 4219

In your last case 3. addFirstAndLast([]) isnt there any index at [0] and [-1]

because the list is empty!

So you should make an example if x == []: return x

Upvotes: 0

ettanany
ettanany

Reputation: 19816

If your list is empty, then you do not have the first and the last elements. Try the following to solve your problem:

def add_first_and_last(x):
    if x:
        return x[0] + x[-1]
    else:
        return 0  # Or whatever you want

You can also try:

def add_first_and_last(x):
    return x[0] + x[-1] if x else 0

Upvotes: 0

Sven
Sven

Reputation: 2889

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

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

Upvotes: 2

Mike
Mike

Reputation: 1215

Of course, in your 3rd case there are no items, hence no relevant index.

Upvotes: 0

DeepSpace
DeepSpace

Reputation: 81684

The last test case passes an empty list. An empty list has neither [0] nor [-1] elements.

Upvotes: 0

Related Questions