On 31.05.2016 07:27, Matthew Tanous wrote:
Currently, the use of the (*) operator on a list is to duplicate a list by creating multiple references to the same object. While this works intuitively for immutable objects (like [True] * 5) as these immutable references are replaced when the list is assigned to, it makes the operator nigh unusable for mutable objects.
The most obvious case is when the operator is duplicated in a sequence like this:
arr = [[True] * 5] * 5
This does not create a matrix-like arrangement of the immutable truth variable, but instead creates a list of 5 references to the same list, such that a following assignment like arr = False will not change just that one index, but every 4th element of each list in the outer list.
It is my opinion that the sequence repetition operator should be modified to make copies of the objects it is repeating, rather than copying references alone. I believe this would both be more intuitive from a semantic point of view and more useful for the developer.
This would change the operator in a way that is mostly unseen in current usage ( * 3 would still result in [5, 5, 5]) while treating mutable nesting in a way that is more understandable from the apparent intent of the syntax construction.
* How would you determine whether a list element is mutable or not ?
* How would you copy the elements ?
* For which object types would you want to change the behavior ?
I agree that the repeat operator can sometimes create confusing and unwanted object structures if not used correctly, but it's main purpose it to repeat the already existing objects, not to copy them, so the current behavior still is conceptually correct.