On Thu, Mar 17, 2022, 5:23 AM Steven D'Aprano <steve@pearwood.info> wrote:
On Thu, Mar 17, 2022 at 01:21:24AM +0900, Stephen J. Turnbull wrote:

> MRAB writes:
>
>  > I'm wondering whether an alterative could be a function for splicing
>  > sequences such as lists and tuples which would avoid the need to create
>  > and then destroy intermediate sequences:
>  >
>  >      splice(alist, i, 1 + 1, [value])
>
> Does this make sense for lists?

I don't see why not.

> I don't see how you beat
>
>     newlist = alist[:]
>     newlist[index_or_slice] = value_or_sequence_respectively

We know the advantages of an expression versus a statement (or pair of
statements). If this was Ruby, we could use a block:


    function(arg, {newlist = alist[:];
                   newlist[i] = value}, another_arg)


but it isn't and we can't.


> (instead of newlist = alist[:i] + [value] + alist[i+1:], which
> involves creating 4 lists instead of 1).

Indeed, the splice function could call a `__splice__` dunder that
specialises this for each type. It is hard to see how to write a
completely generic version.


--
Steve

Not a pro or con just an observation: since dictionaries are ordered now people would also (somewhat reasonably, imo) want to be able to splice them, too.