I am new to Python, so I apologize if this question is naive.
I consider a list elements = [3, 6, 7]
. I would like to write a series of instructions which transform the list l = [[], [], []]
into l = [[3], [6], [7]]
. If I write the (naive) code below :
pos = 0
for i in range(3):
l[i].append(elements[i])
print(l)
then the output is not as I expected. Indeed, the list l
becomes l=[[3, 6, 7], [3, 6, 7], [3, 6, 7]]
. My reasoning was the following one : when i=0
only l[0]
(the first element of l
) should be modified. However, it is not the case. After the first run in the loop, the list l
is : l = [[3], [3], [3]]
. Where am I wrong ?
Of course, this could be easily solved using list comprehension:
l = [[elements[j]] for j in range(3)]