0

I try this code below

lst = [[]] * n
lst[0].append(1)

If i print the cod, the result is

[[1], [1], [1], [1], [1], [1]]

And then I try manual way to make an empty list like below

lst = [[], [], [], [], [], []]
lst[0].append(1)

The result showing up

[[1], [], [], [], [], []]

Is there any differences between lst = [[]] * n and lst = [[], [], [], [], [], []] ?

  • This exact question was just asked a few hours ago. :) https://stackoverflow.com/questions/60348228/python-filling-array-in-the-loop#comment106753907_60348228 – Mateen Ulhaq Feb 22 '20 at 10:36
  • Try printing `id` of each inner list when you do `[[]]*n`. – Ch3steR Feb 22 '20 at 10:36
  • Sorry, my friend, I'm new here, but I got it. I cant search the keyword for the article, so I made new one. Thanks for the response – Rijal Islami Feb 23 '20 at 04:31

1 Answers1

0

when you multiply your list of lists with n you are repeating only the reference to the same initial list so basically you have only one list and many references to the same list and when you are modifying one element you are modifying all; when you create "by hand" you have different lists

kederrac
  • 16,819
  • 6
  • 32
  • 55