Skip to content

Instantly share code, notes, and snippets.

@crodriguez1a
Last active September 20, 2019 13:06
Show Gist options
  • Save crodriguez1a/fca36e049053e3905728e2c70a0032b9 to your computer and use it in GitHub Desktop.
Save crodriguez1a/fca36e049053e3905728e2c70a0032b9 to your computer and use it in GitHub Desktop.
Lesson - Generator Expressions
"""
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.
Ref: https://www.geeksforgeeks.org/python-list-comprehensions-vs-generator-expressions/
"""
from sys import getsizeof
comp = [i for i in range(10000)]
gen = (i for i in range(10000))
#gives size for list comprehension
x = getsizeof(comp)
print("x = ", x)
#gives size for generator expression
y = getsizeof(gen)
print("y = ", y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment