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