Dictionary instantiation?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Dec 7 16:41:54 EST 2007


On Fri, 07 Dec 2007 11:56:14 +0100, Bruno Desthuilliers wrote:

> Also, modifying a sequence in place while iterating over it is a *very*
> bad idea.

That's somewhat of an exaggeration, surely. Some sorts of modifications 
are more error-prone than others, and deserves your warning e.g. 
inserting or deleting items (as the OP was doing). But modifying the 
items themselves isn't risky at all. E.g. instead of this:

L = []
for x in xrange(1000000):
    L.append(result_of_some_calculation(x))


a perfectly reasonable optimization technique for large lists is:

L = [None]*1000000
for i,x in enumerate(L):
    L[i] = result_of_some_calculation(x)


The second avoids needing to re-size the list repeatedly, which is quite 
slow.


-- 
Steven



More information about the Python-list mailing list