There's a lot of confusion about what the various kinds of things you can iterate over in Python. I'll attempt to collect definitions for all of the relevant terms, and provide examples, here, so I don't have to go over the same discussions in the same circles every time.

Some previous posts that may be relevant here:


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 asliststr, and tuple) and some non-sequence types like dictfile 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 alsoiteratorsequence, 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.
Iterator is a subtype of iterable—that is, every iterator is an iterable. But other things are iterables too, like sequences. What distinguishes an iterator is that calling iter with an iterator returns the iterator itself. This means that iterators are inherently one-shot: once you iterate an iterator, you've got an empty iterator.

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 liststr,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.
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().
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.

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.
8

View comments

It's been more than a decade since Typical Programmer Greg Jorgensen taught the word about Abject-Oriented Programming.

Much of what he said still applies, but other things have changed. Languages in the Abject-Oriented space have been borrowing ideas from another paradigm entirely—and then everyone realized that languages like Python, Ruby, and JavaScript had been doing it for years and just hadn't noticed (because these languages do not require you to declare what you're doing, or even to know what you're doing). Meanwhile, new hybrid languages borrow freely from both paradigms.

This other paradigm—which is actually older, but was largely constrained to university basements until recent years—is called Functional Addiction.
5

I haven't posted anything new in a couple years (partly because I attempted to move to a different blogging platform where I could write everything in markdown instead of HTML but got frustrated—which I may attempt again), but I've had a few private comments and emails on some of the old posts, so I decided to do some followups.

A couple years ago, I wrote a blog post on greenlets, threads, and processes.
6

Looking before you leap

Python is a duck-typed language, and one where you usually trust EAFP ("Easier to Ask Forgiveness than Permission") over LBYL ("Look Before You Leap"). In Java or C#, you need "interfaces" all over the place; you can't pass something to a function unless it's an instance of a type that implements that interface; in Python, as long as your object has the methods and other attributes that the function needs, no matter what type it is, everything is good.
1

Background

Currently, CPython’s internal bytecode format stores instructions with no args as 1 byte, instructions with small args as 3 bytes, and instructions with large args as 6 bytes (actually, a 3-byte EXTENDED_ARG followed by a 3-byte real instruction). While bytecode is implementation-specific, many other implementations (PyPy, MicroPython, …) use CPython’s bytecode format, or variations on it.

Python exposes as much of this as possible to user code.
6

If you want to skip all the tl;dr and cut to the chase, jump to Concrete Proposal.

Why can’t we write list.len()? Dunder methods C++ Python Locals What raises on failure? Method objects What about set and delete? Data members Namespaces Bytecode details Lookup overrides Introspection C API Concrete proposal CPython Analysis

Why can’t we write list.len()?

Python is an OO language. To reverse a list, you call lst.reverse(); to search a list for an element, you call lst.index().
8

Many people, when they first discover the heapq module, have two questions:

Why does it define a bunch of functions instead of a container type? Why don't those functions take a key or reverse parameter, like all the other sorting-related stuff in Python? Why not a type?

At the abstract level, it's often easier to think of heaps as an algorithm rather than a data structure.
1

Currently, in CPython, if you want to process bytecode, either in C or in Python, it’s pretty complicated.

The built-in peephole optimizer has to do extra work fixing up jump targets and the line-number table, and just punts on many cases because they’re too hard to deal with. PEP 511 proposes a mechanism for registering third-party (or possibly stdlib) optimizers, and they’ll all have to do the same kind of work.
3

One common "advanced question" on places like StackOverflow and python-list is "how do I dynamically create a function/method/class/whatever"? The standard answer is: first, some caveats about why you probably don't want to do that, and then an explanation of the various ways to do it when you really do need to.

But really, creating functions, methods, classes, etc. in Python is always already dynamic.

Some cases of "I need a dynamic function" are just "Yeah? And you've already got one".
1

A few years ago, Cesare di Mauro created a project called WPython, a fork of CPython 2.6.4 that “brings many optimizations and refactorings”. The starting point of the project was replacing the bytecode with “wordcode”. However, there were a number of other changes on top of it.

I believe it’s possible that replacing the bytecode with wordcode would be useful on its own.
1

Many languages have a for-each loop. In some, like Python, it’s the only kind of for loop:

for i in range(10): print(i) In most languages, the loop variable is only in scope within the code controlled by the for loop,[1] except in languages that don’t have granular scopes at all, like Python.[2]

So, is that i a variable that gets updated each time through the loop or is it a new constant that gets defined each time through the loop?

Almost every language treats it as a reused variable.
4
Blog Archive
About Me
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.