Speed difference between iterating over generators and lists
问题 In the following trivial examples there are two functions that sort a list of random numbers. The first method passes sorted a generator expression, the second method creates a list first: import random l = [int(1000*random.random()) for i in xrange(10*6)] def sort_with_generator(): return sorted(a for a in l) def sort_with_list(): return sorted([a for a in l]) Benchmarking with line profiler indicates that the second option ( sort_with_list ) is about twice as fast as the generator