Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generator expressions vs. list comprehensions

When should you use generator expressions and when should you use list comprehensions in Python?

# Generator expression (x*2 for x in range(256))  # List comprehension [x*2 for x in range(256)] 
like image 639
readonly Avatar asked Sep 06 '08 20:09

readonly


People also ask

What is the difference between a list comprehension and generator expression?

So what's the difference between Generator Expressions and List Comprehensions? The generator yields one item at a time and generates item only when in demand. Whereas, in a list comprehension, Python reserves memory for the whole list. Thus we can say that the generator expressions are memory efficient than the lists.

Why use a generator over a list?

The main advantage of generator over a list is that it take much less memory. We can check how much memory is taken by both types using sys. getsizeof() method.

Does list comprehension create a generator?

List comprehensions are eager but generators are lazy. In list comprehensions all objects are created right away, it takes longer to create and return the list. In generator expressions, object creation is delayed until request by next() . Upon next() generator object is created and returned immediately.

Are list comprehensions more efficient?

Conclusions. List comprehensions are often not only more readable but also faster than using “for loops.” They can simplify your code, but if you put too much logic inside, they will instead become harder to read and understand.


1 Answers

John's answer is good (that list comprehensions are better when you want to iterate over something multiple times). However, it's also worth noting that you should use a list if you want to use any of the list methods. For example, the following code won't work:

def gen():     return (something for something in get_some_stuff())  print gen()[:2]     # generators don't support indexing or slicing print [5,6] + gen() # generators can't be added to lists 

Basically, use a generator expression if all you're doing is iterating once. If you want to store and use the generated results, then you're probably better off with a list comprehension.

Since performance is the most common reason to choose one over the other, my advice is to not worry about it and just pick one; if you find that your program is running too slowly, then and only then should you go back and worry about tuning your code.

like image 83
Eli Courtwright Avatar answered Sep 29 '22 22:09

Eli Courtwright