Built-in types¶
This chapter introduces some commonly used built-in types. We will cover many other kinds of types later.
Simple types¶
Here are examples of some common built-in types:
Type |
Description |
---|---|
|
integer |
|
floating point number |
|
boolean value (subclass of |
|
text, sequence of unicode codepoints |
|
8-bit string, sequence of byte values |
|
an arbitrary object ( |
All built-in classes can be used as types.
Any type¶
If you can’t find a good type for some value, you can always fall back
to Any
:
Type |
Description |
---|---|
|
dynamically typed value with an arbitrary type |
The type Any
is defined in the typing
module.
See Dynamically typed code for more details.
Generic types¶
In Python 3.9 and later, built-in collection type objects support indexing:
Type |
Description |
---|---|
|
list of |
|
tuple of two |
|
tuple of an arbitrary number of |
|
dictionary from |
|
iterable object containing ints |
|
sequence of booleans (read-only) |
|
mapping from |
|
type object of |
The type dict
is a generic class, signified by type arguments within
[...]
. For example, dict[int, str]
is a dictionary from integers to
strings and dict[Any, Any]
is a dictionary of dynamically typed
(arbitrary) values and keys. list
is another generic class.
Iterable
, Sequence
, and Mapping
are generic types that correspond to
Python protocols. For example, a str
object or a list[str]
object is
valid when Iterable[str]
or Sequence[str]
is expected.
You can import them from collections.abc
instead of importing from
typing
in Python 3.9.
See Using generic builtins for more details, including how you can use these in annotations also in Python 3.7 and 3.8.
These legacy types defined in typing
are needed if you need to support
Python 3.8 and earlier:
Type |
Description |
---|---|
|
list of |
|
tuple of two |
|
tuple of an arbitrary number of |
|
dictionary from |
|
iterable object containing ints |
|
sequence of booleans (read-only) |
|
mapping from |
|
type object of |
List
is an alias for the built-in type list
that supports
indexing (and similarly for dict
/Dict
and
tuple
/Tuple
).
Note that even though Iterable
, Sequence
and Mapping
look
similar to abstract base classes defined in collections.abc
(formerly collections
), they are not identical, since the latter
don’t support indexing prior to Python 3.9.