0 votes
1 view
in Python by (47.8k 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 (107k 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.8k points)
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...