Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python * operator, creating list with default value

How do the following work?

>>> 3*[2]
>>> [2,2,2]
>>> [2]*3
>>> [2,2,2]

I understand that * is the positional expansion operator. Since [2] is a list with a single item, I don't see how 3*[2] expands to anything meaningful, I'd expect a SyntaxError, but that's not the case.

I'm having a hard time searching for an existing answer, all I find are references to *args and **kwargs for passing variadic parameter lists, which don't quite answer my question.

like image 589
ash Avatar asked Jun 13 '26 05:06

ash


1 Answers

* is the multiplication operator. All Python sequences support multiplication. See the Sequence Types documentation:

s * n, n * s
n shallow copies of s concatenated

Note that the copies are shallow; any nested mutable types are not recursively copied too. This can lead to suprising results:

>>> nested = [[None]] * 5
>>> nested
[[None], [None], [None], [None], [None]]
>>> nested[0].append(42)
>>> nested
[[None, 42], [None, 42], [None, 42], [None, 42], [None, 42]]

There is just one nested [None] list, referenced 5 times, not 5 separate list objects.

The *args and **kw variable argument syntax only has meaning in a function definition or in a call (so callable_object(<arguments>)). It doesn't apply here at all. See What does ** (double star) and * (star) do for parameters? for more detail on that syntax.

Sequence types overload the * operator through the object.__mul__() and object.__rmul__() methods (when being the left or right operand in the expression), see Emulating container types for documentation on what hooks sequence types typically implement.

like image 78
Martijn Pieters Avatar answered Jun 14 '26 18:06

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!