-2
list=[3, 1, -1]
list [-1]=list [-2]
print(list)

ok my last post was closed, even though this is not about slicing. There are no semicolons. The question is an exam question from the Python Institute course. I do not understand why the result of this calculation is [3, 1, 1]

Can someone explain me how this works?

Anna
  • 444
  • 1
  • 5
  • 23
  • Does this answer your question? [Negative list index?](https://stackoverflow.com/questions/11367902/negative-list-index) – SamBob Jan 04 '23 at 21:05
  • 2
    so [-1] is accessing the last index while [-2] is accessing the second to last index of the list. when you set the last index equal to the second to last index you are changing the value of the last index to the second to last value giving [3, 1, 1] – Andrew Ryan Jan 04 '23 at 21:05
  • 2
    Because `list[-2]` means "second element from the end", which is 1. You are assigning that to `list[-1]`, which means "the last element". – Tim Roberts Jan 04 '23 at 21:05

2 Answers2

2

list[-1] means "the last item in the list".

list[-2] means "the next-to-last item in the list".

So, list [-1]=list [-2] means "assign the last item in the list to be the same as the next-to-last item in the list".

Honestly, I don't understand your confusion...

John Gordon
  • 29,573
  • 7
  • 33
  • 58
0

A negative index in a python list is counting from the end. I.e., l[-1] points to the last element in the list, l[-2] to the second last and so forth.

Thus

l[-1]=l[-2]

takes the second last value and writes it to the last element. As this is 1 the last element is set to 1, too.

sim
  • 1,148
  • 2
  • 9
  • 18