Search code examples
pythonlist-comprehensiongenerator-expression

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)]

Solution

  • 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.