I am studying for my PCEP and in the practice set there is a syntax for referencing lists I don't understand. Given:
numbers = [2, 3, 5, 8]
print(numbers[numbers[0]])
print(numbers[0])
The first print statement I can't understand, how am I getting 5 as the output? The second statement makes sense, it's how I have done it in the past which is index 0 but what is the first print statement doing? Calling a list within a list like a nested list? And how am I getting to index 2 to get the output of 5?
Thanks in advance for your help/time, it's much appreciated.
I've tried changing the refrenced index and counting through the list twice but often times I am seeing an index out of range response, or a number I wasn't expected. e.g, setting the print statement to
print(numbers[numbers[1]])
Gives me the output of '8' and I don't understand how I am to get there with the index of 1.
CodePudding user response:
It is a similar principle as the parentheses in math. If you have nested parentheses you work from the inside out. In the first example the code solves the inner most number[] list.
So number[0] is 2. Then the code use this converted code to solve the next outer list so you can see it as number[2], instead of number[number[0]].
So number[2] is 5. I do really hope this explanation helps, and I wish you the best in your studies.
CodePudding user response:
Python follows zero based indexing;
numbers[0] is 2
numbers[1] is 3
numbers[2] is 5
numbers[3] is 8
numbers[0]
is 2
So,
print(numbers[numbers[0]])
becomes print(numbers[2])
and numbers[2]
is 5
Similarly,
numbers[1]
is 3
Now,
print(numbers[numbers[1]])
becomes print(numbers[3])
and numbers[3]
is 8
CodePudding user response:
When you have nested expressions and they're confusing you, the easiest way to understand what's happening is to break it up into multiple statements.
print(numbers[numbers[0]])
is equivalent to
temp = numbers[0]
print(numbers[temp])
The first statement sets temp = 2
, so the second statement prints numbers[2]
, which is 5
.