0 votes
1 view
in Python by (32.3k 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 (76.5k 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

Welcome to Intellipaat Community. Get your technical queries answered by top developers !

Categories

...