Reputation: 67
I am having a hard time understanding why the output of this Python code is 1. Just to add, I am just new to programming:
What is the output of the following snippet:
lst = [3, 1, -2]
print(lst[lst[-1]])
Upvotes: 1
Views: 152
Reputation: 86
The negative indexing starts from where the array ends. This means that the last element of the array is the first element in the negative indexing which is -1.
arr = [1, 2, 3, 4, 5]
print (arr[-1]) # output 5
print (arr[-2]) #output 4
#arr[-3] =3
print(arr[arr[-3]]) #output 4
Upvotes: 1
Reputation: 7625
As @Chris mentioned in comments, lst[-1]
is equal to -2, so from lst[lst[-1]]
becomes lst[-2]
. This code picks the second item from back.
Actually, there are always two indices for one item in lists in Python. I hope this schema will help you to better understand:
0 1 2
↓ ↓ ↓
[3, 1, -2]
↑ ↑ ↑
-3 -2 -1
Here you can find a The Basics of Indexing and Slicing Python Lists tutorial.
Upvotes: 1