Click here to Skip to main content
15,565,474 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am currently learning python and working my way through a course, just done an end of module exam. There was one question I got wrong but I don't understand how the output is what it is.

my_list = [3, 1, -2]

The output is 1, can some explain why that is please?

What I have tried:

I have searched around the internet with not luck
Updated 29-Jul-21 12:19pm

1 solution

Python allows negative indexes to lists, with -1 being the last item, -2 the second to last, and so forth.
So your code:
my_list = [3, 1, -2]
Is the equivelant of:
index = my_list[-1]
Since -1 is the last element of the list, index becomes -2, which accesses the second to last element of the list and prints it: 1
Share this answer
Luke 2 29-Jul-21 17:30pm    
Thank you. That helps me understand it completely.
OriginalGriff 29-Jul-21 17:32pm    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900