-2
result_list = [[]]*3
print(result_list) #output [[],[],[]]
result_list[0].append(0)
result_list[1].append(33)
result_list[2].append(2)
print(result_list) #output [[0,33,2],[0,33,2],[0,33,2]]
# ???????????

list = [[],[],[]]
print (list) #output [[],[],[]]
list[0].append(0)
list[1].append(33)
list[2].append(2)
print (list) #output [[0],[33],[2]]
#normal

I want to make a list, where I can say, how many [] there should be (like in the first example with *3), but I want that list to behave like the second example, so that I can append to each [] individually.

wow
  • 1
  • Initialzation is different; in the first one you actually create list where the same list is present 3 times (position [0], [1] and [2] point to the same object) while in the second on you intialize a list with 3 different list. – Mathieu Nov 06 '20 at 12:44

2 Answers2

1
[[]]*3

Actually is making one inner list [] which is referenced 3 times, so you are appending to the same list every time ... the alternative:

result_list = [[] for i in range(3)]
Vasil Yordanov
  • 417
  • 3
  • 14
0

Why doesn't the first list do the same as the second?

Because the * operator on list simply adds new references to the original, so [[]]*3 is equivalent to (but faster than):

container = []
content = []
for _ in range(3):
    container.append(content)

therefore you get the same inner list 3 times, rather than three different lists.

I want to make a list, where I can say, how many [] there should be (like in the first example with *3), but I want that list to behave like the second example, so that I can append to each [] individually.

l = [[] for _ in range(n)]

PS: don't call things list, list is a builtin, don't override builtins.

Masklinn
  • 34,759
  • 3
  • 38
  • 57