Converting a one-item list to an integer
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.
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)
.
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.