0

I encountered this problem when creating lists. Can someone explain why there is a difference between the two lists?

bucket = [ ]

for n in range(5):
    bucket.append([])

lists = [ [ ] ]*(5)
for n in range(5):
    bucket[n].append(n)
    lists[n].append(n)

print bucket
# [[0], [1], [2], [3], [4]]

print lists
# [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

1 Answers1

4
lists = [ [ ] ] * (5)

creates a 5 element list, where each its element is a reference to the same, empty list. So once you add anything to "one" of them - you add to all.

while in the same time appending [] (like with bucket variable) in a loop appends each time new list, so you can add to them independently

lejlot
  • 64,777
  • 8
  • 131
  • 164
  • You can also read a detailed explanation of this behavior (and a work around using list comprehension) in [this recent Ned Batchelder's blog post](http://nedbatchelder.com/blog/201308/names_and_values_making_a_game_board.html). – Ludwik Trammer Oct 06 '13 at 09:38