This is not the best way to create nested lists. Don't do it in your code. Do this instead. However, I'm curious about this way only.
Out of curiosity. I tried googling but all I got is how to do it and not why, and I already know that part.
I was trying to instantiate the following structure with a multiplier:
[[], [], []]
from an unknown number of inner lists, so I wanted to multiply the lists by range(len(other_list))
(this last part is unrelated, so I´ll simplify multiplying by 3 here).
After failing intuitively, with the following expression: [[]] *3
, I learned in another question that you need to represent as multiplying both lists (inner ones and one outer each) instead.
>>[[]] * 3
[[], [], []]
>>[[] * 3]
[[]]
- Why the sentence works that way (it's kind of multiplying the double list first and then doing and extend of the outer list...?)
- Python is usually very intuitive in all its expressions. What makes this one different?
Thanks for the patience. I know this is a weird question :D
CodePudding user response:
It all comes down to how list multiplication is implemented. Unlike numeric values, there isn't a standard idea of what multiplication should mean for a list. There is a great argument that multiplication is meaningless for lists and that an error should be raised.
But the implementers like to do clever things and assigned a meaning to the mathematical operators. For multiplication, the list is extended length * N
elements and the existing values are used to to fill the space. I think the primary motivation is to have a convenient way to prefill a list with default values.
In the first case [[]] * 3
you have a list with a single value: another list. The list is extended to 3 elements and new references to that single list are filled. The print shows [[], [], []]
but somewhat subtly, that's really just 3 references to the single list you started with.
In the second case [[] * 3]
you extend an empty inner list and put the result in an outer list. But that extension is 0 * N
because there isn't anything in the list, so you just end up with [[]]
.
Different collections may choose to do something completely different. If you had a numpy
array arr
, then arr * 3
would multiple each value in arr
by 3 and return to you a new array with the result.