If you look at the source for sorted
, any sequence you pass in will first be copied to the new list.
newlist = PySequence_List(seq);
generator
→ list
is slower than list
→ list
.
>>> timeit.timeit('x = list(l)', setup = 'l = xrange(1000)') 16.656711101531982 >>> timeit.timeit('x = list(l)', setup = 'l = range(1000)') 4.525658845901489
How to make a copy, think about how sorting works. Sorting is not a linear algorithm. We move through the data several times, sometimes looking at the data in both directions. The generator is designed to create a sequence through which we repeat once and only once, from the beginning to somewhere after it. The list allows random access.
On the other hand, creating a list from a generator would mean only one list in memory, while copying a list would mean two lists in memory. A good combination of space-time.
Python uses Timsort , a hybrid of sorting sorting and insertion sorting.
source share