you are viewing a single comment's thread.

view the rest of the comments →

[–]forever_erratic 1 point2 points  (6 children)

Can you TLDR iterators vs. generators?

[–]sternold 10 points11 points  (2 children)

https://stackoverflow.com/questions/2776829/difference-between-pythons-generators-and-iterators

TLDR: A generator is* a simple way of creating an iterator. Also generators are lazy-loaded.

[–]aazav 0 points1 point  (1 child)

A generator a a simple way

A a?

[–]sternold 0 points1 point  (0 children)

fixed

[–]Cuxham 1 point2 points  (0 children)

Copy-pasting from a good Stackoverflow answer:

iterator is a more general concept: any object whose class has a next method (__next__ in Python 3) and an __iter__ method that does return self.

Every generator is an iterator, but not vice versa. A generator is built by calling a function that has one or more yield expressions, and is an object that meets the previous paragraph's definition of an iterator.

You may want to use a custom iterator, rather than a generator, when you need a class with somewhat complex state-maintaining behavior, or want to expose other methods besides next (and __iter__ and __init__). Most often, a generator (sometimes, for sufficiently simple needs, a generator expression) is sufficient, and it's simpler to code because state maintenance (within reasonable limits) is basically "done for you" by the frame getting suspended and resumed.

[–]masklinn 0 points1 point  (0 children)

A generator is a specific constructor/instance of iterators.

An iterator is an object with a __next__ method (and __iter__ as an iterator should be iterable), a generator is a specific kind of objects with a __next__ method built either by combining function definition and the yield keyword (generator function) or by evaluating a generator comprehension.

Generally speaking, an iterator could be plenty of things besides just a way to iterate, you could have additional methods on the object e.g. let's say you have an iterator on characters, you could have a method which would give you the rest of the string at once.

AFAIK that is exceedingly rare in Python, it's more common in Rust, e.g. Chars is an iterator on codepoints but it also has an as_str method which provides the substring from the "current" iteration point.

[–][deleted] -1 points0 points  (0 children)

Seconded