Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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

1 Answer

0 votes
by (106k points)

The generator expression should be used if you're iterating once over anything. But in case if you want to store and use the generated results, then you're advised to use a list comprehension.

The main reason for choosing among one of these is the performance, so it is advised not to worry about performance you can pick anyone. 

def gen():

return (something for something in get_some_stuff())

print(gen()[:2])# generators don't support indexing 

print([5,6] + gen()) # generators can't be added to lists

Related questions

0 votes
1 answer
0 votes
2 answers
asked Sep 17, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...