-3

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)

Anshika Singh
  • 994
  • 12
  • 20
Beatso
  • 75
  • 1
  • 9

3 Answers3

3

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)
2

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
Chris Montanaro
  • 16,948
  • 4
  • 20
  • 29
2

Second last would be myList[-2], nth last is myList[-n] You can read about negative indexing here

Karl Olufsen
  • 186
  • 1
  • 10