Understanding list syntax for PCEP

Question:

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.

Asked By: justRes3t

||

Answers:

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.

Answered By: Le_Me

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.

Answered By: Barmar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.