On 2022-03-15 23:13, Steven D'Aprano wrote:
On Tue, Mar 15, 2022 at 11:16:04AM +1100, Chris Angelico wrote:

> How do we make a new list with a change other than the same slice and
> concatenation we use with tuples?
>
>     alist[:i] + [value] + alist[i+1:]
>
> I mean as an expression, of course we can split it over two statements:
>
>     newlist = alist[:]
>     newlist[i] = value
>
> which is fine, but it does lose the expressiveness of an expression :-)
>

The functional programming style would be mapping most elements to
themselves, and the one you're replacing to the replacement.

No, that doesn't work, because that is replacing by value, not by
position. You're answering the wrong problem.


(Or, if you need to do it with indices, map the range of integers to
either the original element at that index or the replacement.)

You mean this?

     [value if index == i else alist[i] for index in range(len(alist))]

This would be *slightly* less unpythonic:

     [value if index == i else x for (index, x) in enumerate(alist)]


but I would reject both of those in a code review unless you had clear
proof that they were significantly faster or more optimal than the
standard idioms. Which I am confident you won't have.

I'm so confident that they're slower I'm not even going to time it
myself before saying I'm confident they're slower! *wink*

Famous-last-words-ly y'rs,

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])

In Python terms it would be:

    def splice(sequence, start, end, insertion):
        return sequence[ : start] + insertion + sequence[end : ]

but, as I said, without the intermediate sequences, just allocate to the final length and then shallow copy.
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/S6WBZFEHVHI2OFS57HGYGWRNA6CJXWWA/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to