I dont get this code can someone explain howit works cuz it doesnt make any sense to me:

my_list = [3,1,-2]

print (my_list[my_list[-1]])
My_list = [5,6,7,8,9,3,-6]
print (My_list[My_list[My_list[-1]]])

What doesn’t make sense about it?

Try breaking it up:

my_list = [3,1,-2]


My_list = [5,6,7,8,9,3,-6]

ok i got that far but if i switch 1 with another pozitive char(ex. 2,3 etc) it brakes to error. im just not sure from where the list starts

As long as the list is not empty, you can always use -1 as an index.
Whether or not you can use -2, -3, -4 etc depends on the length of the list.
Whether or not you can use an element of the list as an index depends om the value of the element in relation to the length of the list (e.g. you cannot use 9 as an index to a list of 7 elements)

The index -1 means the last element of the list. It’s roughly equivalent to len(mylist) - 1.

In the first case, we get -2 from the [3, 1, 2] list, and use it to index in again (the second one from the end), which gives 1.

In the second case, we get -6 from the last spot [5,6,7,8,9,3,-6] list; index with that again (by counting 6 from the end), which gives 6; and index again (counting from the front; remember that the first index is 0, not 1) to get -6 again.


if you’re familiar with function composition, this is basically the same idea but in software. You take the output result of one function as the input to the next.

ok i got thanks to everyone