After seeing the discussion here: Python - generate the time difference I got curious. I also initially thought that a generator is faster than a list, but when it comes to
I also initially thought that a list comprehension is faster than a list
What do you mean faster than a list? Do you mean faster than an explicit for
? For that I will say it depends: The list comprehension is more like a syntactic sugar, but it's very handy when it comes to simple loop.
but when it comes to sorted() I don't know. Is there any benefit to sending a generator expression to sorted() rather than a list?
The main difference between List comprehensions and Generator expressions is that the Generator expressions avoid the overhead of generating the entire list at once. Instead, they return a generator object which can be iterated one by one, so the Generator expressions are more likely used to save memory usage.
But you have to understand one thing in Python: It's very hard to tell if one way is faster (optimistic) than another way just by looking at it, and if you want to do that you should use timeit for benchmarking (and benchmarking is more complex than just running one timeit on a single machine).
Read this for more info about some optimization techniques.