The reason this is the case is because CPython is implemented in C and uses C arrays as the backing store for lists, and you must reallocate and move the elements before adding an element to the front of the list.
To answer the second half of your question, "Does this hold true for Java also?" The answer is yes, both primitive arrays in Java and ArrayList in Java do not allow prepending to the list without reallocating and moving the elements.
Also, your code is flawed because you are assigning to result
and not results
, so you aren't actually causing quadratic performance as stated in the question. A better way to demonstrate this behavior would be the following:
results = []
for i in range(1000000):
results.insert(0, f(i))
And the append version:
results = []
for i in range(1000000):
results.append(f(i))
Or using the timeit
module:
$ python -m timeit 'results = []' 'for i in range(10000): results.insert(0, i)'
10 loops, best of 3: 50.9 msec per loop
$ python -m timeit 'results = []' 'for i in range(10000): results.append(i)'
1000 loops, best of 3: 794 usec per loop