Why is my code faster with append() in a loop than with a large list?

David david at pythontoo.com
Sun Jul 5 20:48:39 EDT 2009


Xavier Ho wrote:
> (Here's a short version of the long version below if you don't want to 
> read:)
> 
> Why is version B of the code faster than version A? (Only three lines 
> different)
> 
> Version A: http://pastebin.com/f14561243
> Version B: http://pastebin.com/f1f657afc
I don't know but here is the diff for someone that may;

1c1,2
< # This one only took 8 seconds on my machine. Wow?
---
 >
 > # This one took hours to compute, overnight.
28c29
<     powers = [0, 0]
---
 >     powers = [0] * (num + 1)
32c33
<             powers[factor-1] += 1
---
 >             powers[factor] += 1
35d35
<             powers.append(0)
55c55
<     n += 1
\ No newline at end of file
---
 >     n += 1


-- 
Powered by Gentoo GNU/Linux
http://linuxcrazy.com



More information about the Python-list mailing list