Some previous posts that may be relevant here:
- Creating a new sequence type is easy
- Lazy cons lists and its followup Lazy Python lists
- Swift-style map and filter views
iteration
Iteration is what a for loop does (whether a for statement, a comprehension, or the C-API equivalent). It's also, of course, what functions like map, zip, list, and islice do under the covers.
The thing you iterate (loop) over is an iterable.
The way you iterate over it (usually implicitly, with a for loop) is to call the iter function, which gives you an iterator. You then call next on the iterator until it raises StopIteration. This is called the iteration protocol.
Iterators are always iterables—if you call iter with an iterator, you just get the same iterator back. The reverse is, of course, not true.
I'm cheating a bit here, because the iteration protocol is actually defined in terms of the dunder methods __iter__ and __next__ (or the slots tp_iter and tp_next, for C extension types) rather than the functions iter and next, and includes a fallback for iterating over old-style sequence-like things that don't define iterability but do define subscripting with contiguous indices starting from 0. But that rarely comes up nowadays—and the iter function wraps up that fallback. So, you can unread this paragraph.
abstract base class (ABC)
Abstract base classes complement duck-typing by providing a way to define interfaces when other techniques likehasattr() would be clumsy or subtly wrong (for example with magic methods). ABCs introduce virtual subclasses, which are classes that don’t inherit from a class but are still recognized by isinstance() and issubclass(); see the abcmodule documentation. Python comes with many built-in ABCs for data structures (in the collections.abc module), numbers (in the numbers module), streams (in the io module), import finders and loaders (in the importlib.abcmodule). You can create your own ABCs with the abc module.
Many of the types described below have an ABC, in the collections.abc module, that defines the type in terms that can be tested from within the language. For example, every iterable should be a subtype of collections.abc.Iterable.
This isn't always perfect (for example, a type that responds to the iter function, but doesn't return an iterator, isn't really a valid iterable, even if it's a collections.abc.Iterable subtype as far as issubclass is concerned). That's usually not a problem unless someone is deliberately obfuscating their code—except in one case. Many third-party collection types do not subtype the relevant ABCs. For example, a third-party sequence may not be a subtype of collections.abc.Sequence, even though it supports all of the right methods with the right semantics. So, in a discussion, is someone shows "issubclass(Spam, Sequence) == True", that can be taken as proof that Spam is a sequence (unless you have reason to believe that it's intentionally or accidentally being misleading—as was the case for range in Python 3.1…), but "issubclass(Spam, Sequence) == False" doesn't prove that Spam isn't a sequence.
iterable
An object capable of returning its members one at a time. Examples of iterables include all sequence types (such aslist, str, and tuple) and some non-sequence types like dict, file objects, and objects of any classes you define with an __iter__() or __getitem__() method. Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(), ...). When an iterable object is passed as an argument to the built-in functioniter(), it returns an iterator for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not necessary to call iter() or deal with iterator objects yourself. The for statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See alsoiterator, sequence, and generator.Fundamentally, an iterable is something that you can use in a for loop. Everything else described here is an iterable. Functions like map, filter, zip, enumerate, etc. can all take any iterable.
iterator
An object representing a stream of data. Repeated calls to the iterator’s __next__() method (or passing it to the built-in function next()) return successive items in the stream. When no more data are available a StopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls to its __next__() method just raiseStopIteration again. Iterators are required to have an __iter__() method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted. One notable exception is code which attempts multiple iteration passes. A container object (such as a list) produces a fresh new iterator each time you pass it to the iter() function or use it in a for loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container.
More information can be found in Iterator Types.
There is no concrete type "iterator". Files are iterators. So are the results of generator functions. Many built-in iterable types (like list, range, and set) have their own custom iterator types. They all support the Iterator ABC, but they're not related in any other way.
Iterators are generally lazy—that is, they only produce elements one at a time, on demand. This isn't inherent to the type, it's just that there's very little good reason to ever create a non-lazy iterator; you'd just be wasting time and memory for no benefit.
generator iterator
An object created by a generator function.
Each yield temporarily suspends processing, remembering the location execution state (including local variables and pending try-statements). When the generator iterator resumes, it picks-up where it left-off (in contrast to functions which start fresh on every invocation).
A generator function is a function with a "yield" or "yield from" expression in it. When you call it, what you get back is a generator iterator. You also get generator iterators from generator expressions.
A generator iterator is, as the name implies, an iterator. Generator iterators also support other methods like send, which aren't relevant here.
Generator iterators are obviously inherently lazy—although there's nothing stopping you from writing "yield from f.readlines()", which would in practice be non-lazy.
The word "generator" on its own is ambiguous. According to the glossary and the reference docs for generators, it should refer to generator functions. However, the in-language name "generator", the ABC "collections.abc.Generator", and the function "inspect.isgenerator" all refer to generator iterators (and "inspect.isgeneratorfunction" refers to generator functions). If it isn't clear from the context which one you're talking about, don't use the word on its own.
sequence
An iterable which supports efficient element access using integer indices via the __getitem__() special method and defines a __len__() method that returns the length of the sequence. Some built-in sequence types are list, str,tuple, and bytes. Note that dict also supports __getitem__() and __len__(), but is considered a mapping rather than a sequence because the lookups use arbitrary immutable keys rather than integers.A sequence—something like list, str, or range—is an iterable, but it's not an iterator. In particular, it's always a reusable iterable—you can loop over a list as many times as you want and get the whole list each time.
The collections.abc.Sequence abstract base class defines a much richer interface that goes beyond just__getitem__() and __len__(), adding count(), index(), __contains__(), and __reversed__(). Types that implement this expanded interface can be registered explicitly using register().
Many sequences are non-lazy, like list, but some are lazy, like range.
Sometimes, the word "sequence" is confusingly used to mean any reusable non-iterator iterable, or even any non-iterator iterable, rather than specifically a sequence.
Sometimes you'll see the term "almost-sequence", to refer to something which supports indexing, but doesn't support the entire sequence protocol. Before Python 3.2, range as such a type. Even in 3.5, the term is still relevant—an almost-sequence is what you need to get the "fallback" iteration behavior. NumPy arrays are almost-sequences in this sense.
non-iterator iterable
There is no official term for something that's an iterable but not an iterator (which may be why the term "sequence" is sometimes confusingly used for it).But this is a useful concept to have. It's any type that you can call iter on it, that doesn't return itself. Sequences like list, mappings like dict, views like dict_values, and many other types are all non-iterator iterables.
Most non-iterator iterables are reusable, but there's nothing in the protocol that guarantees this. Sometimes the two concepts are confusingly conflated.
reusable iterable
There is no official term for something that's an iterable, but not an iterator, which can iterate over the same items repeatedly (and, usually, in parallel).
But this is a useful concept to have. Sequences like list, mappings like dict, mapping views like dict_values, and many other types are reusable iterables.
As mentioned above, sometimes this concept is conflated with the previous one, and sometimes the word "sequence" is confusingly used for both of them.
view
The objects returned from dict.keys(), dict.values(), and dict.items() are called dictionary views. They are lazy sequences that will see changes in the underlying dictionary. To force the dictionary view to become a full list uselist(dictview). See Dictionary view objects.In addition to the specific meaning from the glossary, the word "view" is also used for any non-iterator iterable that similarly provides a view of (possibly some of) the (possibly transformed) elements of some other object.
For example, if you have some object that supports the buffer protocol, you can create a memoryview object referencing all or part of its buffer. This is, as the name implies, a view into that other object. If you slice a memoryview, you get another view into the same object.
Similarly, when you slice a NumPy array, what you get back is another NumPy array, which shares the same storage, but accesses it differently.
Note that not all views are sequences. (In fact, dictionary view objects are not, despite what the glossary says. This is an example of the word "sequence" being used loosely for "non-iterator iterable".)
lazy
A lazy iterable creates its elements on demand. For example, range(1, 1000, 3) doesn't create 333 element up-front and store them all in memory; instead, whenever you try to access one (by indexing, by iteration, or otherwise), it calculates it on the fly.
Generally, iterators are lazy, as are views, but something can be lazy without being either—like range.
An iterable that creates each element the first time it's needed, but caches them, is usually still considered lazy. (In fact, this is how lists work in languages built around laziness. But notice that most such languages use "cons lists", which give you a very natural way to release part of the list without releasing the whole thing—so, e.g., you can zip a list and its tail, iterate the result, and it only keeps two elements in memory at the same time. That isn't as easy to do in Python.)
virtual
The word "virtual" in this context isn't defined anywhere, but it's used in other definitions. For example, older versions of the documentation defined range as a "virtual sequence". (I'm not sure the term still appears anywhere in the documentation as of 3.5, but it's still sometimes used in discussions.)
The intended distinction seems to be that a lazy iterable that's not a view onto an actual iterable, but instead computes its values directly.
Looked at another way: a range object is actually providing a view into something—an infinite iterable consisting of all of the integers—but that something doesn't actually exist anywhere in memory—hence "virtual".
container
The term "container" isn't defined anywhere, although there is a corresponding ABC.
The ABC defines non-iterator iterables that support the "in" operator.
However, the term is often used more loosely, as a term for non-iterator iterables in general, or a vague term meaning "sequences, almost-sequences, mappings, sets, views, and other similar things". There aren't too many non-iterator iterables that aren't "similar things", or that don't support "in" testing, so usually there's no confusion here.
collection
The term "collection" isn't defined anywhere. It's often used as a vague synonym for iterable, or an even-vaguer synonym for container.
View comments