List comprehension vs Generator Expression - less memory


Let's use a bigger range of numbers and create the corresponding list and generator. Then check the size of both of them. You can see the list is much bigger. That's becuse the list already contains all the elements, while the generator contains only the promise to give you all the elements.

As we could see in the previous example, this is not an empty promise, you can indeed iterate over the elements of a generator just as you can iterate over the elements of a list.

However, you cannot access an arbitrary element of a generator because the generator is not subscriptable.


examples/generators/generator_expression.py
import sys

lst = [n*2 for n in range(1000)] # List comprehension
gen = (n*2 for n in range(1000)) # Generator expression

print(sys.getsizeof(lst))
print(sys.getsizeof(gen))
print()

print(type(lst))
print(type(gen))
print()

print(lst[4])
print()

print(gen[4])

9016
112

<class 'list'>
<class 'generator'>

8

Traceback (most recent call last):
  File "generator_expression.py", line 17, in <module>
    print(gen[4])
TypeError: 'generator' object is not subscriptable

List Comprehension vs Generator Expressions