Click here to Skip to main content
15,890,348 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.


Python
my_list = [3, 1, -2]
print(my_list[my_list[-1]])



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

What I have tried:

I have searched around the internet with not luck
Posted
Updated 29-Jul-21 11:19am
v3

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]
print(my_list[my_list[-1]])
Is the equivelant of:
index = my_list[-1]
print(my_list[index])
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
 
Comments
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