| I think you're both right and wrong. mixmastamyk's comment implies that (s)he believes that Python lists are, under the hood, linked lists. This is wrong. Python lists are ultimately backed by C arrays. This is why get() and set() are O(1), and insert() is O(n). However, dynamically resizing an array to support append operations, if you're not stupid, takes amortized constant time. Individual operations may be O(n). Python implementers, happily, are not stupid. However, insert() operations do require "defragmenting". So, the primary question mixmastamyk asked about the cost of def squares(n):
sq = []
for i in xrange(n):
sq.append(i*i)
return sq
is totally correct, but a lot of the sub-reasoning is wrong. |
I suppose using an array must improve performance in typical cases, while the resizing (a linked-list advantage) happens less often.