1

I created a list of 3 empty lists:

>>> l = [[]]*3
>>> l
[[], [], []]

then added an item in the second one:

>>> l[1].append("j")

but it added it on every lists:

>>> l
[['j'], ['j'], ['j']]

why?

arthur.sw
  • 11,052
  • 9
  • 47
  • 104
  • 3
    Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) You don't have a "list of lists" here, you have a list of *list*, singular. – jasonharper May 07 '21 at 16:41

1 Answers1

1

My guess is that the [[]]*3 operator adds 3 times the same list as a reference ; so modifying one list modifies every others.

To create 3 empty different lists:

>>> l = [[] for r in range(3)]
>>> l[1].append("j")
>>> l
[[], ['j'], []]
arthur.sw
  • 11,052
  • 9
  • 47
  • 104
  • Yes, Im going to go ahead and say you are correct. Because if you manually enter sublists and try and append it works as intended. ```l = [[],[],[]] l[0].extend("j") print(l)``` – Buddy Bob May 07 '21 at 16:23