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
The most Pythonic way to convert a list of strings to a list of ints is to use the list comprehension [int(x) for x in strings] . It iterates over all elements in the list and converts each list element x to an integer value using the int(x) built-in function.
Approach #3 : Using map() Another approach to convert a list of multiple integers into a single integer is to use map() function of Python with str function to convert the Integer list to string list. After this, join them on the empty string and then cast back to integer.
The most Pythonic way to convert a list of floats fs to a list of integers is to use the one-liner fs = [int(x) for x in fs] . It iterates over all elements in the list fs using list comprehension and converts each list element x to an integer value using the int(x) constructor.
In Python, a list is created by placing elements inside square brackets [] , separated by commas. A list can have any number of items and they may be of different types (integer, float, string, etc.). A list can also have another list as an item.
You're slicing the list, which return lists. Here, you should use indexes instead:
firstDigit = x[0]
lastDigit = x[-1]
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.
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With