Noah Dukehart
Noah Dukehart

Reputation: 11

explain this line of code (lists)

print ( [ 2 ∗ [ k ] for k in range ( 3 ) ] [ 2 ] [ 1 ] )

this is the code and it says the answer is 2, will someone explain it to me. i don't understand exactly what the code is asking for and i don't know how it is getting 2 as an answer i'm assuming it has something to do with the iteration but i don't really fully understand it. i have a lot of difficulty with lists in general and this was a question that was both on the practice exam and the real exam and i want to understand it

Upvotes: 1

Views: 47

Answers (2)

Azmi Kamis
Azmi Kamis

Reputation: 901

You could break the single statement into 4 actually and it will make more sense naturally.

>>> range ( 3 )
[0, 1, 2]
>>> [ 2 * [ k ] for k in [0, 1, 2] ] # where 2*[0] returns [0,0] and so on
[[0, 0], [1, 1], [2, 2]]
>>> [[0, 0], [1, 1], [2, 2]][2]
[2, 2]
>>> [2, 2][1]
2

Upvotes: 0

Chad S.
Chad S.

Reputation: 6631

for k in range(3) will set k to 0, then 1, then 2. So then 2*[k] will make a list with two elements where each element is the current value of k. The result after the list comprehension is equivalent to [ [0,0], [1,1], [2,2] ][2][1] Since the [2] after the list comprehension will access the 3rd element of the list (the list at index 2), and the [1] will access the second element of the sublist, the result is 2

    0      1      2     <-- first level indices 

[ [0,0], [1,1], [2,2] ]
                   ^--- this is the item you get 
   0 1    0 1    0 1    <-- second level indices

Upvotes: 2

Related Questions