Python Forum
need help in referencing a list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: need help in referencing a list (/thread-30685.html)



need help in referencing a list - n00bdev - Nov-01-2020

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!


RE: need help in referencing a list - Larz60+ - Nov-01-2020

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



RE: need help in referencing a list - buran - Nov-01-2020

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