15,565,474 members
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 12:19pm
v3

## Solution 1

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

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)

Top Experts
Last 24hrsThis month
 Dave Kreskowiak 75 OriginalGriff 60 k5054 55 Prerak Patel 40 Graeme_Grant 35
 OriginalGriff 200 Dave Kreskowiak 145 Richard MacCutchan 120 k5054 120 Graeme_Grant 80

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