Equivalents of Ruby's "!" methods?
Terry Reedy
tjreedy at udel.edu
Mon Aug 25 12:57:21 EDT 2008
Paul McGuire wrote:
> Pythonistically speaking, even though a dict is a mutable thing, I'm
> learning that the accepted practice for methods like this is not so
> much to update in place as it is to use generator expressions to
> construct a new object.
I disagree. The convention is that mutation methods should return None.
> For example, given a list of integers to 100,
> instead of removing all of the even numbers (with the attendant
> hassles of updating a list while iterating over it), just create a new
> list of the numbers that are not even.
This is because each removal is O(n), making the entire process O(n*2),
whereas a new list is O(n) -- and the hassle of remembering to iterate
in reverse when doing removals.
> Perhaps I am overgeneralizing from comments I have read here on c.l.py
> about creating new lists instead updating old ones.
I think so. Removals and insertions are importantly different from
change in place. If I wanted to square each number in a list, and *did
not need the original list*, I would not hesitate to do it in place.
The newish sorted() and reversed() built-ins were meant to complement
list.sort and list.reverse, not replace them.
tjr
More information about the Python-list
mailing list