Why does [0] * 5
create a list [0, 0, 0, 0, 0]
, rather than [[0], [0], [0], [0], [0]]
?
Doesn't the *
operator duplicate [0]
5 times resulting in [[0], [0], [0], [0], [0]]
?
Why does [0] * 5
create a list [0, 0, 0, 0, 0]
, rather than [[0], [0], [0], [0], [0]]
?
Doesn't the *
operator duplicate [0]
5 times resulting in [[0], [0], [0], [0], [0]]
?
Just like math:
[0] * 5 = [0] + [0] + [0] + [0] + [0]
, which is [0, 0, 0, 0, 0]
.
I think people would be more surprised if [0] + [0]
suddenly became [[0], [0]]
.
For strings, tuples, and lists, +
is an append operator. This multiplication holds true for all of them.
Reading the Python docs for sequence types it seems that it is because [0] * 5
is shorthand for [0] + [0] + [0] + [0] + [0]
(just as multiplication is in math a shorthand for addition; it works the same when "multiplying" lists).
No, it multiplies elements and [0] list (just like mathematical set) has one element 0, not [[0]].
Use statement below to create [[0], [0], [0], [0], [0]]:
[[0]*1]*5
Note that the list you've mentioned above is a 2d list, so you must use * operator in right way. It means your list has 5 rows and 1 column.
Below is the real result: enter image description here