Hello,
I am running below program in Python Interpreter, I am trying to know how the value of p[1] [0] is getting printed.
Per my understanding, value of p[1][0] should be 2, 3, 1 but giving output of 2.
Can someone investigate that and help me to know the answer.
Below is the code for your reference.
>>>q=[2,3]
>>>p=[1,q,4]
>>>len(p) #print length of p
3 #output
>>>p[1] #print p
[2,3] #output
>>>p[1] [0] #print p
2 #output

Sachin SinghPosted Jan 10, 2024, 3:22 PM
In Python, when you access an element of a list using indexing, the value retrieved is the value at that particular index. In your case:
q = [2, 3] p = [1, q, 4]When you do
p[1], it returns the element at index 1 in the listp, which is the list[2, 3]. So,p[1]is[2, 3].Now, when you do
p[1][0], you are accessing the element at index 0 within the listp[1]. Sincep[1]is[2, 3],p[1][0]refers to the element at index 0 within[2, 3], which is2.Therefore, the output of
p[1][0]is indeed2.Aradhana TripathiPosted Jan 10, 2024, 3:34 PM
Thanks Sachin Singh for quick response, it helped!