Reputation: 23
x = [1,[2,[3,4],5],6]
print(x[1][1][1])
Could you explain it to me, why the result is 4
.
Upvotes: 1
Views: 142
Reputation: 8017
x = [1,[2,[3,4],5],6]
What x[1][1][1]
does is:
Takes the second element:
[2,[3,4],5]
second element from that list:
[3,4]
second element
4
So it makes perfect sense.
It's the second not first element because lists in python are numerated from 0.
Upvotes: 0
Reputation: 24905
x = [1,[2,[3,4],5],6]
is actually like below when you look at it as index based:
InnerList-2 Index-> 0 1
InnerList-1 Index-> 0 1 2
OuterList Index-> 0 1 2
x = [1,[2,[3,4],5],6]
So, this translates to:
x[1] -> [2,[3,4],5]
x[1][1] -> [3,4]
x[1][1] -> 4
Upvotes: 0
Reputation: 530
x = [1,[2,[3,4],5],6]
x[1] = [2,[3,4],5]
x[1][1] = [3,4]
x[1][1][1] = 4
Remember you start indexing from 0. So x[0] = 1
and x[1] = the entire nested list
Also remember that a nested list is detected as a single entity. In this case,
x
contains 3 elements which are 1
,[2,[3,4],5]
and 6
. The second element now has an index position of 1
and also contains 3 elements which are 2
,[3,4]
and 5
. Same for the nested loop [3,4]
.
Upvotes: 0
Reputation: 16792
Since indices is 0
based.
x = [1,[2,[3,4],5],6]
# The element placed on 1 of [1,[2,[3,4],5],6] i.e. [2, [3, 4], 5]
print(x[1])
# The element placed on 1 of [2, [3, 4], 5] i.e. [3, 4]
print(x[1][1])
# The element placed on 1 of [3, 4] i.e. 4
print(x[1][1][1])
OUTPUT:
[2, [3, 4], 5]
[3, 4]
4
Upvotes: 2