Convert a list from one item to an integer

I was asked to take a list of integers (x), add the first value and the last value to the list, and then return an integer with the sum. I used the following code for this, but the problem is that when I try to estimate the amount, it is actually a list of one element instead of the whole. I tried applying it to an int, but I can't get it to work.

def addFirstAndLast(x): lengthOfList = len(x) firstDigit = x[0:1] lastDigit = x[lengthOfList:lengthOfList-1] sum = firstDigit + lastDigit return sum 
+7
source share
3 answers

Use indexes

You slice a list that returns lists. Here you should use indexes instead:

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

Why the wrong choice for you:

When you execute x[0:1] , you take a 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 

Executing x[0:2] , for example, will return elements 0 and 1.

+13
source

It all boils down to the following:

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

In Python, a negative list index means: start indexing to the right of the list 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) .

+4
source

Use Slice Designation :

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

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

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

+4
source

All Articles