0

I am looking to understand what purpose a generator serves.

For example, in the following

what is the practical difference between

iter([x for x in range(1,10)])

and

(x for x in range(1,10))

?

why should I use a generator at all?

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • `[x for x in range(1,10)]` is going to create the real list. If you have 1 billion elements, it will use several gigabytes. Not the case with the generator expression (which is also useless, just use `range(1,10)` – Jean-François Fabre May 27 '20 at 08:20
  • `iter` provides interfaces for `next()` method, useful to iterate manually on your list. – Jean-François Fabre May 27 '20 at 08:20
  • @Jean-FrançoisFabre Thanks, your answer is appreciated, but I am aware of what would happen if the list had a billion elements. I am looking to find out whether the specific two pieces of code above have any distinction. I chose a short list deliberately. This is an attempt to get at the presence or lack of a conceptual distinction within the language construct. The code is a toy problem in which to contemplate that. – Ponder Stibbons May 27 '20 at 08:25
  • I have closed as duplicate as the duplicate explains everything I wanted to post as an answer and more. You can refine your question/post another one if something isn't clear. – Jean-François Fabre May 27 '20 at 08:26
  • in general it's better to use builtins vs generator comprehensions because the loop is done in a compiled language for the first one so it may be faster. it's also shorter. – Jean-François Fabre May 27 '20 at 08:28

0 Answers0