Is there a better way of doing this?

Steven D'Aprano steve at pearwood.info
Sat Mar 7 23:49:56 EST 2009


Gabriel Genellina wrote:

> Imagine you're working with someone side by side. You write a note in a
> piece of paper, put it into an envelope, and hand it to your co-worker. He
> opens the envelope, throws it away, takes the note and files it inside a
> folder right at the end. And you do this over and over. What's wrong in
> this story?
> 
> Please save our trees! Don't waste so many envelopes

Nice story, but the moral "conserve what you use" is not always good advice.
Bits are not envelopes -- sometimes it is more environmentally friendly to
throw them away and create new ones. Consider:

mylist[:] = [x for x in mylist if not condition(x)]

versus:

for i in xrange(len(mylist)-1, -1, -1):
    x = mylist[i]
    if condition(x):
        del mylist[i]


The first "wastefully" creates a new list, and the second tries to recycle
bits by deleting the items in place. Unless mylist is so huge that your
computer starts thrashing trying to make two copies in memory, the first is
not only simpler to write and understand, but almost certainly much, much
faster than the second.

That's not the case in this specific example, but as a general principle,
it's worth remembering that it's often better to be wasteful with temporary
objects than to use miserly algorithms invented for machines with 64K of
memory.

(The same lessons can apply for re-world considerations as well. Recycling
doesn't just happen, it requires energy and water and other costs. If the
environmental costs of recycling something are worse than the environmental
costs of throwing it away and making a new one, then recycling that object
is actually harmful. But I digress.)


-- 
Steven




More information about the Python-list mailing list