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,


-- 
Steve
_______________________________________________
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/FNBYYLIBVFSL65DIXLR2OD6YU3JO5QA2/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to