Python Forum
need help in referencing a list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
need help in referencing a list
#1
Sad 
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!
Reply
#2
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
Reply
#3
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  name 'lblstatus' is not defined when referencing a label KatManDEW 4 1,540 Apr-21-2022, 12:33 PM
Last Post: KatManDEW
  Dictionary Referencing nickdavis2017 1 1,613 Nov-20-2021, 06:24 PM
Last Post: deanhystad
  Referencing string names in df to outside variables illmattic 1 1,369 Nov-16-2021, 12:47 PM
Last Post: jefsummers
  Referencing a fixed cell Mark17 2 2,072 Dec-17-2020, 07:14 PM
Last Post: Mark17
  Issue referencing new instance from other class nanok66 3 2,239 Jul-31-2020, 02:07 AM
Last Post: nanok66
  referencing another method in a class Skaperen 6 2,671 Jul-02-2020, 04:30 AM
Last Post: Skaperen
  Theory behind referencing a dictionary rather than copying it to a list sShadowSerpent 2 2,092 Mar-24-2020, 07:18 PM
Last Post: sShadowSerpent
  "not defined" error in function referencing a class Exsul 2 3,686 Mar-27-2019, 11:59 PM
Last Post: Exsul
  Prevent Variable Referencing Th3Eye 4 2,891 Oct-03-2018, 07:01 PM
Last Post: buran
  Tree insertion and variable referencing hshivaraj 3 3,336 Dec-10-2017, 04:29 PM
Last Post: Windspar

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020