[Python-ideas] proposed methods: list.replace / list.indices

Ned Batchelder ned at nedbatchelder.com
Sun Dec 30 15:10:01 CET 2012


On 12/30/2012 5:46 AM, Terry Reedy wrote:
> On 12/29/2012 10:25 PM, David Kreuter wrote:
>
>> I think it would be nice to have a method in 'list' to replace certain
>> elements by others in-place. Like this:
>>
>>      l = [x, a, y, a]
>>      l.replace(a, b)
>>      assert l == [x, b, y, b]
>>
>> The alternatives are longer than they should be, imo. For example:
>>
>>      for i, n in enumerate(l):
>>          if n == a:
>>              l[i] = b
>
> I dont see anything wrong with this. It is how I would do it in 
> python. Wrap it in a function if you want. Or write it on two line ;-).

I wonder at the underlying philosophy of things being accepted or 
rejected in this way.  For example, here's a thought experiment: if 
list.count() and list.index() didn't exist yet, would we accept them as 
additions to the list methods?  By Terry's reasoning, there's no need 
to, since I can implement those operations in a few lines of Python.  
Does that mean they persist only for backwards compatibility?  Was their 
initial inclusion a violation of some "list method philosophy"?  Or is 
there a good reason for them to exist, and if so, why shouldn't 
.replace() and .indexes() also exist?

The two sides (count/index and replace/indexes) seem about the same to me:

- They are unambiguous operations.  That is, no one has objected that 
reasonable people might disagree about how .replace() should behave, 
which is a common reason not to add things to the stdlib.
- They implement simple operations that are easy to explain and will 
find use.  In my experience, .indexes() is at least as useful as .count().
- All are based on element equality semantics.
- Any of them could be implemented in a few lines of Python.

What is the organizing principle for the methods list (or any other 
built-in data structure) should have? I would hate for the main 
criterion to be, "these are the methods that existed in Python 2.3," for 
example.   Why is .count() in and .replace() out?

>
>> If there is a reason not to add '.replace' as built-in method,
>
> There is a perfectly good python version above that does the necessary 
> search and replace as efficiently as possible. Thank you for posting it.
>

You say "as efficiently as possible," but you mean, "as algorithmically 
efficient as possible," which is true, they are linear, which is as good 
as it's going to get.  But surely if coded in C, these operations would 
be faster.

--Ned.



More information about the Python-ideas mailing list