-4

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)

1
  • 5
    myList[-2]…!? If 2 is a variable, -n…? Commented Apr 6, 2020 at 13:31

3 Answers 3

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) 
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.