Chapter 3. Essential Containers
Let’s now delve further into the tools of the Python language.
Python comes with a suite of built-in data containers.
These are data types that are used to hold many other variables. Much like you might
place books on a bookshelf, you can stick integers or floats or strings into these
containers.
Each container is represented by its own type and has its own unique properties
that define it. Major containers that Python supports are
list
, tuple
, set
, frozenset
, and dict
. All but frozenset
come with their
own literal syntax so that creating them is effortless. dict
is by far
the most important of these, for reasons that we’ll see in “Dictionaries” and
in Chapter 6.
Before we dive in, there are two important Python concepts to understand:
-
Mutability
-
Duck typing
A data type is mutable if its value—also known as its state—is allowed to change after it has been created. On the other hand, a data type is immutable if its values are static
and unchangeable once it is created. With immutable data you can create new variables
based on existing values, but you cannot actually alter the original values.
All of the data types we have dealt with so far—int
, float
, bool
, and str
—are immutable.
It does not make sense to change the value of 1
. It just is 1
, and so
integers are immutable.
Containers are partially defined by whether they are mutable or not, and this
determines where and how they are used.
Duck typing, on the other hand, is one of the core principles ...
Get Effective Computation in Physics now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.