Why is [[]]*10 the way to create a list of 10 empty lists in python instead of [[]*10]?

Viewed 130

Why does [[]]*10 make a list of ten empty lists? [[]*10] makes more sense to me.

5 Answers

I think the best explanation for you may be to look at [1, 2] * 4, which gives you [1, 2, 1, 2, 1, 2, 1, 2]. Multiplication with a list on the left makes copies of the elements of the list, not the list itself.

[] * 10 makes ten copies of no elements whatsoever and gives you [].

[[]] * 10 gives you ten copies of [], which is what you're looking for.


@blckknght points out, and it's worth emphasizing, that * repeats the elements of the list, but the elements themselves are not copied.

>>> X = [1, 2, 3, 4, 5]
>>> Y = [X] * 2
>>> Y
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]

Y now contains X itself twice, not two copies of X.

>>> Y[0] is X
True
>>> X[0] = 'a'
>>> Y
[['a', 2, 3, 4, 5], ['a', 2, 3, 4, 5]]
>>> 

The "better" way to create a list of 10 empty lists is to use a list comprehension

[[] for _ in range(10)]

[[]] * 10 will create a list of 10 references to the exact same list and will lead to interesting behaviour

x = [[]] * 10
x[0].append(1)
print(x)

Outputs

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

Why [[] * 10] doesn't behave as you want is covered by other answers

Because [] + [] == [] in Python. So for your preferred syntax, the * operator is basically repeatedly adding [] to an empty list and getting another empty list back.

Here are my explanations:

  • [[] * 10] multiplies the values within the list, it gives [[]] because there are no values in the sublist, it's just an empty list, so as we all know 0 * 10 is 0.

  • [[]] * 10 works because it multiples the value inside (as you know from above, I said it multiplies the values), here there are values it's the empty list [], it multiples the [[]] ten times, so it multiplies the value ten times, so the value ten times would be: [[], [], [], [], [], [], [], [], [], []]

  1. [[]]*10 : This mean you have 10 "list in list".

[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]]

2.[[]*10] This mean you have one list contain 10 list:

[[],[],[],[],[],[],[],[],[],[]]

Related