Here is some code that I wrote using Python:
from math import sqrt
abundant_list = []
for i in range(12,28123+1):
dividor_list = [1]
for j in range(2, int(sqrt(i))+1):
if i%j == 0:
dividor_list.extend([i/j,j])
if sum(dividor_list) > i:
abundant_list.append(i)
print abundant_list
As you can see, the code is really trying to be efficient as much as possible.
There is any difference if I use list.append twice, or list.extend just once?
I know it can be minor differences, but I would really like to know that 🙂
Here’s a simple benchmark. My results (os-X, 10.5.8, core2duo, FWIW):
And the same ordering of the results my linux box (Ubuntu, x86-64 core i7):
To me, this says that
extendis quicker thanappend, but that creating alistis relatively expensive compared to creating atupleEDIT
Pointed out in the comments below, because of the immutability of tuples, the interpreter can optimize the creation of the tuple out (it creates the tuple once and re-uses it over and over). If we change the code to:
The timings are virtually identical:
Although
tuplestill consistently beats the list version and barely edges out theappendversion for all of the trials I have done.One thing that I’m taking away from this is that if you’re iterating over an object that consists of all literals, choose a
tupleover alist. If it doesn’t consist entirely of literals, then it really doesn’t matter whether you chooselistortuple.