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.

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

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").

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

6

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

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'

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.

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 reall

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.

1

Many languages have a for-each loop.

4

When the first betas for Swift came out, I was impressed by their collection design. In particular, the way it allows them to write map-style functions that are lazy (like Python 3), but still as full-featured as possible.

2

In a previous post, I explained in detail how lookup works in Python.

2

The documentation does a great job explaining how things normally get looked up, and how you can hook them.

But to understand how the hooking works, you need to go under the covers to see how that normal lookup actually happens.

When I say "Python" below, I'm mostly talking about CPython 3.5.

7

In Python (I'm mostly talking about CPython here, but other implementations do similar things), when you write the following:

def spam(x): return x+1 spam(3) What happens?

Really, it's not that complicated, but there's no documentation anywhere that puts it all together.

2

I've seen a number of people ask why, if you can have arbitrary-sized integers that do everything exactly, you can't do the same thing with floats, avoiding all the rounding problems that they keep running into.

2

In a recent thread on python-ideas, Stephan Sahm suggested, in effect, changing the method resolution order (MRO) from C3-linearization to a simple depth-first search a la old-school Python or C++.

1

Note: This post doesn't talk about Python that much, except as a point of comparison for JavaScript.

Most object-oriented languages out there, including Python, are class-based. But JavaScript is instead prototype-based.

1

About a year and a half ago, I wrote a blog post on the idea of adding pattern matching to Python.

I finally got around to playing with Scala semi-seriously, and I realized that they pretty much solved the same problem, in a pretty similar way to my straw man proposal, and it works great.

About a year ago, Jules Jacobs wrote a series (part 1 and part 2, with part 3 still forthcoming) on the best collections library design.

1

In three separate discussions on the Python mailing lists this month, people have objected to some design because it leaks something into the enclosing scope. But "leaks into the enclosing scope" isn't a real problem.

2

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.

8

Python has a whole hierarchy of collection-related abstract types, described in the collections.abc module in the standard library. But there are two key, prototypical kinds. Iterators are one-shot, used for a single forward traversal, and usually lazy, generating each value on the fly as requested.

2

There are a lot of novice questions on optimizing NumPy code on StackOverflow, that make a lot of the same mistakes. I'll try to cover them all here.

What does NumPy speed up?

Let's look at some Python code that does some computation element-wise on two lists of lists.

2

When asyncio was first proposed, many people (not so much on python-ideas, where Guido first suggested it, but on external blogs) had the same reaction: Doing the core reactor loop in Python is going to be way too slow. Something based on libev, like gevent, is inherently going to be much faster.

Let's say you have a good idea for a change to Python.

1

There are hundreds of questions on StackOverflow that all ask variations of the same thing. Paraphrasing:

lst is a list of strings and numbers. I want to convert the numbers to int but leave the strings alone.

2

In Haskell, you can section infix operators. This is a simple form of partial evaluation. Using Python syntax, the following are equivalent:

(2*) lambda x: 2*x (*2) lambda x: x*2 (*) lambda x, y: x*y So, can we do the same in Python?

Grammar

The first form, (2*), is unambiguous.

1

Many people—especially people coming from Java—think that using try/except is "inelegant", or "inefficient". Or, slightly less meaninglessly, they think that "exceptions should only be for errors, not for normal flow control".

These people are not going to be happy with Python.

2

If you look at Python tutorials and sample code, proposals for new language features, blogs like this one, talks at PyCon, etc., you'll see spam, eggs, gouda, etc. all over the place.

Most control structures in most most programming languages, including Python, are subordinating conjunctions, like "if", "while", and "except", although "with" is a preposition, and "for" is a preposition used strangely (although not as strangely as in C…).

There are two ways that some Python programmers overuse lambda. Doing this almost always mkes your code less readable, and for no corresponding benefit.

1

Some languages have a very strong idiomatic style—in Python, Haskell, or Swift, the same code by two different programmers is likely to look a lot more similar than in Perl, Lisp, or C++.

There's an advantage to this—and, in particular, an advantage to you sticking to those idioms.

1

Python doesn't have a way to clone generators.

At least for a lot of simple cases, however, it's pretty obvious what cloning them should do, and being able to do so would be handy. But for a lot of other cases, it's not at all obvious.

5

Every time someone has a good idea, they believe it should be in the stdlib. After all, it's useful to many people, and what's the harm? But of course there is a harm.

3

This confuses every Python developer the first time they see it—even if they're pretty experienced by the time they see it:

>>> t = ([], []) >>> t[0] += [1] --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <stdin> in <module>()

11
Blog Archive
About Me
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.