19

I've been asked to accept a list of integers (x), add the first value and the last value in the list, and then return an integer with the sum. I've used the following code to do that, but the problem I have is that when I try to evaluate the sum it's actually a one-item list instead of an integer. I've tried to cast it to an int but I can't seem to get it to work.

def addFirstAndLast(x):  
    lengthOfList = len(x)  
    firstDigit = x[0:1]  
    lastDigit = x[lengthOfList:lengthOfList-1]  
    sum = firstDigit + lastDigit  
    return sum  
Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
Scott
  • 385
  • 1
  • 3
  • 16
  • What should the behavior be if `x` contains one number? Should it return `x[0]` or `2*x[0]`? – 000 Apr 08 '13 at 20:03

4 Answers4

22

Use indexes

You're slicing the list, which return lists. Here, you should use indexes instead:

firstDigit = x[0]
lastDigit = x[-1]

Why is slicing wrong for you:

When you do x[0:1], you're taking the list of items from the beginning of the list to the first interval.

 item0, item1, item2, item3
^ interval 0
        ^ interval 1
              ^ interval 2 
                     ^ interval 3    

Doing x[0:2], for example, would return items 0 and 1.

Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116
5

It all boils down to this:

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

In Python, a negative list index means: start indexing from the right of the list in direction to the left, where the first position from right-to-left is -1, the second position is -2 and the last position is -len(lst).

Óscar López
  • 232,561
  • 37
  • 312
  • 386
5

Use Slice Notation:

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

x[0] = will give you 0th index of the list, first value.

x[-1] = will give you the last element of the list.

Community
  • 1
  • 1
herinkc
  • 381
  • 2
  • 13
3

I'm just adding a special case here for anyone who is struggling like I was with list comprehensions, which return a list. @Thomas Orozco's answer saved me. This is a dead-simple example:

mylist=[1,5,6]
[el for el in mylist if el==5]
>> [5] #returns a *list* containing the element -- not what I wanted

Adding a subscript extracts the element from the list.

[el for el in mylist if el==5][0]
>> 5 #returns the element itself

If you want multiple elements returned as a tuple (not a list), you can enclose the whole statement:
tuple([el for el in l if (el==5 or el==6)])

John
  • 1,018
  • 12
  • 19