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 = [[], [], [], [], [], []] ?

3
  • This exact question was just asked a few hours ago. :) stackoverflow.com/questions/60348228/… Commented Feb 22, 2020 at 10:36
  • Try printing id of each inner list when you do [[]]*n. Commented Feb 22, 2020 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 Commented Feb 23, 2020 at 4:31

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.