-2

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)]
Odile
  • 175
  • 3
  • How did you actually create `l`? Did you actually do it with the line `l = [[], [], []]`? Include in your code snippet the line that creates `l`. – BrenBarn Mar 21 '17 at 18:06
  • 1
    It looks like you tried `l = [[]]*3`. – chepner Mar 21 '17 at 18:07
  • Your code works for me in Python3 and Python2. Some of the code you show here (probably the definition of `l`) is not the real code you used for the wrong result. – mkiever Mar 21 '17 at 18:10

2 Answers2

1

The problem is in the part of the code you haven't posted (that's why you should post complete examples when you ask questions here).

What has happened is that l contains three references to the same list. When you append an element to that list and then print l, you still see three copies of that list.

You need to create l in a way that truly makes three separate lists:

l = [ [], [], [] ] #good
l = [ [] for x in range(3) ] #good
l = [ [] ] * 3  #bad
0

Three copies of the same list

It appears that you've constructed your list 'l' not from three empty lists, but of three references to the same single empty list. This means that any changes done to it through l[0] are reflected also if you look at the same list through l[1].

Peteris
  • 3,281
  • 2
  • 25
  • 40