New GitHub issue #115267 from pvlkhn:<br>

<hr>

<pre>
# Feature or enhancement

### Proposal:

### Issue:

The current implementation of list concatenation using the + operator in CPython always allocates new memory, resulting in unnecessary copying for temporary objects, especially noticeable in scenarios involving recursive list creation

```python
def recursive_arange_via_sum(start, stop):
    assert start < stop
    if start == stop - 1:
        return [start]
    return recursive_arange_via_sum(start, stop - 1) + [stop - 1]
```
The same performance issue extends to set and tuple objects modifications

### Proposal:

Introduce an optimization by using internally in-place versions to modify lists/sets with exactly one reference instead of creating a new ones. Similar optimization already [implemented](https://github.com/python/cpython/blob/5a173efa693a053bf4a059c82c1c06c82a9fa8fb/Objects/unicodeobject.c#L11032) for strings. While lists/sets are mutable, and operations like append, extend, and the += operator are available, using in-place versions internally could enhance performance without sacrificing code clarity as in the example below:

```python
def recursive_arange_via_append(start, stop):
 assert start < stop
    if start == stop - 1:
        return [start]
 recursive_result = recursive_arange_via_append(start, stop - 1)
 recursive_result.append(stop - 1)
    return recursive_result
```
While `recursive_arange_via_append` works much faster than `recursive_arange_via_sum` many people are [in fact](https://github.com/search?q=%22%29+%2B+%5B%22+language%3APython&type=code&l=Python) sacrificing performance for a clarity in such code constructions. Most of them are not recursive, but still there is unnecessary copy

### Note

For tuples, such cases are relatively rare, and I don't see a straightforward solution (there is no inplace operator implemented), but further analysis can be performed if deemed useful

### Has this already been discussed elsewhere?

No response given

### Links to previous discussion of this feature:

_No response_
</pre>

<hr>

<a href="https://github.com/python/cpython/issues/115267">View on GitHub</a>
<p>Labels: type-feature</p>
<p>Assignee: </p>