Python Forum

Full Version: need help in referencing a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello!

So I tried to search about this, but can't find an explanation regarding the output.

a = [3, 1, -2]

print(a[a[-1])
Output:
1
I initially thought that this would return an error, but it ran fine. I also thought that it would just reference the last element which is -2 thinking that -1 in the print() is referring to the index.

I just started learning Python. Thanks in advance for any help!
to print entire list:
for item in a:
    print(item)
To print last item:

print(a[-1])
Your item: a[a[-1]] would be:
Output:
a indexed by a[-1] = a[-2] = 1
First of all - your code will indeed raise an error because there is missing closing ] :-)

now, look at
a = [3, 1, -2]
print(a[a[-1]])
a[-1] will return -2, so this is equivalent to print(a[-2]). and a[-2] is 1