[x*x for x in data] is a list comprehension. It computes every item immediately and stores the whole list in memory.
(x*x for x in data) is a generator expression. It computes nothing yet. It produces one item at a time, only when you ask for the next one, and uses almost no memory.
A generator can be used only once. After you have looped over it, it is exhausted.
Use a list when you need the results more than once, need len(), indexing or slicing, or the data is small. Use a generator when the data is large, or when you only need to loop once, or feed it into something like sum():
total = sum(x*x for x in range(10_000_000))
That never builds a ten-million-item list.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
The brackets decide.
[x*x for x in data]is a list comprehension. It computes every item immediately and stores the whole list in memory.(x*x for x in data)is a generator expression. It computes nothing yet. It produces one item at a time, only when you ask for the next one, and uses almost no memory.A generator can be used only once. After you have looped over it, it is exhausted.
Use a list when you need the results more than once, need len(), indexing or slicing, or the data is small. Use a generator when the data is large, or when you only need to loop once, or feed it into something like
sum():That never builds a ten-million-item list.