I know how to get the last item in a list myList
:
myList[-1]
But how would I get the second last, or the nth last item in a string, without doing something like this:
myList[len(myList)-(n-1)
I know how to get the last item in a list myList
:
myList[-1]
But how would I get the second last, or the nth last item in a string, without doing something like this:
myList[len(myList)-(n-1)
You can just keep using the reverse index.
# Second to list
myList[-2]
# n last
n=3
myList[-3]
In the second case, it would return the third from last. You can also iterate over the list using this
for item in myList[::-1]:
print(item)
Increase your negative index to count back from the end of a list
>>> l = [1, 2, 3, 4, 5]
>>> l[-1]
5
>>> l[-2]
4
>>> l[-3]
3
Second last would be myList[-2], nth last is myList[-n] You can read about negative indexing here