On Thu, 2006-11-16 at 07:32 -0800, Danny Colligan wrote:
> Carsten mentioned that generators are more memory-efficient to use when
> dealing with large numbers of objects. Is this the main advantage of
> using generators?  Also, in what other novel ways are generators used
> that are clearly superior to alternatives?

The memory efficiency is definitely a major advantage. Generators allow
you to efficiently produce, manipulate, and consume sequences of
arbitrary length. The length of the sequence could even be potentially
infinite, which is impossible to handle when you're working with actual
lists.

The memory efficiency aside, it's more elegant to write something like
this:

    def squares(n):
      for i in range(n):
        yield i**2

than something like this:

    def squares(n):
      result = []
      for i in range(n):
        result.append(i**2)
      return result

-Carsten


-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to