How to Access the Last Item in a List in Python

I am so, so glad you asked. Drum roll.

my_list = [10,20,30,40,50]

print("Last number is:", list[-1])

And the output:

Last number is: 50


What just happened?

Basically, using a negative index will start moving backwards through the list from the end. So to get the second last item would be:

print("Second last number is:", list[-2])

# Output:
# Second last number is: 40

And likewise, to get the last two items:

print("Last two numbers:", list[-2:])

# Output:
# Last two numbers: [40, 50]


Leave a Reply

Your email address will not be published.