3.4. More Python typesΒΆ

We’ve learned about numbers and strings, but the world does not consist of numbers and strings alone, not even in a programming language. First of all there is the world outside the program. There are different types for files (or, more precisely, for the streams by which we communicate with them) and for the endpoints of our connections to the outside world (for instance, in talking to another host on the internet or to a printer). But even before we get to the outside world, there is the basic need to have data that is structured, in a way we now try to make clear.

Sometimes we need data that contains other data. In Python, this kind of datum is called a container.

Figure Python container type tree shows the basic Python container types. All serve different needs. The container types are

Python type tree

Python container type tree

One feature that all containers share is they support the in operator:

>>> x = 'abcde'
>>> 'c' in x
True

So containers contain things and x in y checks to see if x is contained in y, and in this case, the character ‘c’ is contained in the string ‘abcde’, so the answer is True. The tree above contains one non-container which is an important special case, file-like objects. These are IO streams for communicating with files or with the user interactively. Technically, file-like objects are not containers, but in many ways you can think of them that way (what they “contain” is lines). They even support the in operator, though it works in a different way (see Files and file IO streams )

Most important Python supertypes

  • Mutable types
  • Containers
  • Iterables

For the authoritative definitions of each of these, see Python.org glossary. The term container is missing from this glossary, though it is clearly a design concept in Python. For a clear discussion (for the geeky) of what a container really is, see the documentation for the Python collections module.

Basic container types