Skip to main content

Built-in types

This page enumerates every type that the interpreter defines and exposes through the builtins module or the runtime. For each, the public methods, the slots they fill, and any non-obvious rules.

Source-of-record: Objects/, Lib/, the standard type hierarchy.

Truth-value testing​

Every type can be tested in a boolean context. The default rule:

Returns false
None, False
Zero of any numeric type: 0, 0.0, 0j, Decimal(0)
Empty containers: '', (), [], {}, set(), range(0)
Objects whose __bool__ returns False
Objects whose __len__ returns 0 (when __bool__ absent)

NoneType​

PropertyValue
Single instanceNone
TruthyNo
SubclassableNo
__repr__'None'

NotImplementedType​

PropertyValue
Single instanceNotImplemented
Returned fromBinary operators that decline to handle.
TruthyRaises DeprecationWarning since 3.9.

EllipsisType​

PropertyValue
Single instanceEllipsis (...)
TruthyYes

Numeric types​

int​

Arbitrary-precision integers. bool is a subclass.

Constructors​

FormResult
int()0
int(x)Truncate x (uses __int__ or __index__).
int("42")Parse decimal.
int("ff", 16)Parse with explicit base 2-36.
int("0xff", 0)Infer base from prefix.

Methods​

MethodReturns
bit_length()Number of bits to represent abs(self).
bit_count()Number of 1 bits (popcount).
to_bytes(length, byteorder, *, signed=False)Big/little-endian byte string.
from_bytes(bytes, byteorder, *, signed=False)Class method.
as_integer_ratio()(self, 1).
is_integer()Always True.
__floor__, __ceil__, __round__Self.
__index__Self.
numerator, denominatorself, 1.
real, imagself, 0.
conjugate()Self.

bool​

Subclass of int. Singletons True == 1, False == 0.

ConstructorResult
bool()False
bool(x)True if x is truthy, else False.

bool cannot be subclassed.

float​

IEEE 754 double.

Constructors​

FormResult
float()0.0
float(x)Numeric coerce.
float("1.5")Parse text.
float("inf")Positive infinity.
float("nan")NaN.

Methods​

MethodReturns
as_integer_ratio()Exact (numerator, denominator).
is_integer()True if integral.
hex()Hex string representation.
fromhex(s)Class method; inverse of hex.
__round__(ndigits=None)Banker's rounding.
real, imag, conjugate()Self, 0.0, self.

complex​

Pair of double. Constructors: complex(), complex(real, imag=0), complex("1+2j").

Attribute / methodReturns
.realReal part.
.imagImaginary part.
.conjugate()Reflection over the real axis.

Iterator types​

A type is an iterator if it implements __iter__ (returning self is conventional) and __next__. Calling __next__ returns the next value or raises StopIteration.

IteratorSource
iter(seq)Built-in.
iter(callable, sentinel)Calls callable until it returns sentinel.
Generatoryield-containing function.
map, filter, zipLazy iterators over their arguments.
range_iteratoriter(range(...)).
enumerate, reversedBuilt-ins.

Sequence types​

Common operations (immutable)​

OpReturns
x in s, x not in sbool
s + tConcatenation.
s * n, n * sRepetition.
s[i]Element.
s[i:j], s[i:j:k]Slice.
len(s)Length.
min(s), max(s)Extremes.
s.index(x[, i[, j]])Index of first occurrence.
s.count(x)Number of occurrences.

Common operations (mutable)​

OpEffect
s[i] = xAssign element.
s[i:j] = tSlice replacement.
del s[i], del s[i:j]Delete.
s.append(x)Append.
s.extend(t) / s += tExtend.
s.insert(i, x)Insert at index.
s.pop([i])Remove and return.
s.remove(x)Remove first occurrence.
s.reverse()In-place reverse.
s.clear()Empty.
s.copy()Shallow copy.
s *= nRepeat in place.

list​

Mutable sequence of references. Resized geometrically. list.sort is stable Timsort:

MethodEffect
list.sort(*, key=None, reverse=False)In-place sort.
list.copy()Shallow copy.

tuple​

Immutable fixed-size sequence. Methods are only .count and .index. Named tuples (collections.namedtuple, typing.NamedTuple) are subclasses adding named field access.

range​

Lazy arithmetic progression range(start, stop, step). Hashable (__hash__ based on the produced sequence).

PropertyDescription
.startStart value.
.stopExclusive endpoint.
.stepStep.

str​

Sequence of Unicode code points. PEP 393 kinded storage: UCS-1, UCS-2, or UCS-4 depending on the maximum code point.

Methods (selected):

MethodReturns
capitalize, casefold, lower, upper, swapcase, titleCased copy.
count, index, rindex, find, rfindSubstring search.
startswith, endswithPrefix/suffix test.
lstrip, rstrip, stripStrip whitespace or given chars.
center, ljust, rjust, zfillPadding.
split, rsplit, splitlinesSplit into list.
partition, rpartitionThree-way split at separator.
replace, translate, maketransReplacement.
joinJoin an iterable of strings.
encode(encoding='utf-8', errors='strict')Encode to bytes.
format, format_mapstr.format machinery.
isalnum, isalpha, isascii, isdecimal, isdigit, isidentifier, islower, isnumeric, isprintable, isspace, istitle, isupperPredicates.
removeprefix, removesuffixPrefix/suffix removal.
expandtabs(tabsize=8)Tab expansion.

bytes​

Immutable byte sequence. Constructors: bytes(), bytes(int), bytes(iterable), bytes(string, encoding), bytes.fromhex(s).

Methods mirror str (decode, hex, split, replace, etc.) but operate on bytes. Element access yields int, not a length-1 bytes.

bytearray​

Mutable counterpart of bytes. Adds append, extend, insert, pop, remove, reverse, clear, copy, +=, *=.

memoryview​

View over a buffer-supporting object. Has .tobytes(), .tolist(), .cast(format[, shape]), .release(), plus attributes format, itemsize, ndim, shape, strides, readonly, c_contiguous, f_contiguous, contiguous, nbytes, obj.

Set types​

set / frozenset​

OperationsetfrozensetReturns
len(s)YYint
x in sYYbool
s.isdisjoint(other)YYbool
s.issubset(other) / <=YYbool
s.issuperset(other) / >=YYbool
s.union(*others) / |YYnew set
s.intersection(*others) / &YYnew set
s.difference(*others) / -YYnew set
s.symmetric_difference(o) / ^YYnew set
s.add(x)Y--
s.remove(x)Y--
s.discard(x)Y--
s.pop()Y-element
s.clear()Y--
Augmented update |=, &=, -=, ^=Y-self

Mapping types​

dict​

Insertion-ordered. Two internal layouts: combined (key+value contiguous) and split (keys shared between instances of the same type for __slots__-free classes).

OperationReturns
len(d)int
d[k]value or __missing__ or KeyError
d[k] = v-
del d[k]-
k in dbool
iter(d)key iterator
d.copy()shallow copy
d.clear()-
d.get(k[, default])value or default
d.setdefault(k[, default])value, inserting default if absent
d.pop(k[, default])value
d.popitem()(k, v) LIFO
d.update(other) / d |= othermerge
d | othernew merged dict
d.keys(), d.values(), d.items()view objects
dict.fromkeys(iter[, value])classmethod

Dict views​

d.keys(), d.values(), d.items() return view objects.

ViewImplements
dict_keysSet-like operations, iteration, length.
dict_valuesIteration, length. Not set-like.
dict_itemsSet-like (when values are hashable), iteration, length.

Mutating the dict during view iteration raises RuntimeError.

mappingproxy​

Read-only view of a dict. Used for class __dict__.

Function and method types​

TypeDescription
functionUser-defined Python function.
methodBound user method.
builtin_function_or_methodBuilt-in or C-level callable.
method-wrapperBound C-level slot method.
wrapper_descriptorUnbound C-level slot method.
staticmethodDescriptor: bypass self.
classmethodDescriptor: bind to class.
functools.partialPartial application.

Function attributes​

AttributeMeaning
__name__Short name.
__qualname__Qualified name.
__module__Defining module.
__doc__Docstring.
__code__Code object.
__globals__Globals dict.
__defaults__Tuple of positional defaults.
__kwdefaults__Dict of keyword-only defaults.
__closure__Tuple of cell objects (or None).
__dict__Attribute storage.
__annotations__Annotation dict (lazy).
__type_params__PEP 695 type params.
__wrapped__Set by functools.wraps.

type metaobject​

type is the default metaclass. Attributes:

AttributeMeaning
type.__name__Short name.
type.__bases__Base classes.
type.__mro__C3 linearisation.
type.__subclasses__()Direct subclasses.
type.__instancecheck__isinstance hook.
type.__subclasscheck__issubclass hook.

type(name, bases, dict) constructs a new class dynamically.

Module type​

A module object has:

AttributeMeaning
__name__Module name.
__doc__Module docstring.
__file__Source file (if any).
__loader__Loader instance.
__spec__ModuleSpec.
__package__Package name.
__path__Search path (packages only).
__dict__Namespace.
__builtins__Builtins reference.
__annotations__Module-level annotations.

slice​

slice(stop), slice(start, stop), slice(start, stop, step). Attributes: .start, .stop, .step. Method .indices(length) returns a tuple of three ints clamped to the sequence length.

Generic alias and union types​

list[int] and friends create types.GenericAlias instances. They forward __call__ and __getattr__ to their origin. int | str creates a types.UnionType instance.

types module aliases​

NameDescription
types.FunctionTypeSame as function.
types.MethodTypeSame as method.
types.GeneratorTypeGenerator object type.
types.CoroutineTypeCoroutine object type.
types.AsyncGeneratorTypeAsync generator object type.
types.MappingProxyTypeRead-only dict view.
types.SimpleNamespaceAttribute-based namespace.
types.ModuleTypeModule type constructor.
types.TracebackTypeTraceback object type.
types.FrameTypeFrame object type.
types.CodeTypeCode object type.
types.CellTypeClosure cell type.

Gopy status​

TypeState
All numeric, sequence, mapping, set typesComplete.
bytearray, memoryviewComplete.
Function / method typesComplete.
type and metaclass machineryComplete.
slice, generic alias, union typeComplete.
ModulesComplete.
Buffer protocolComplete for built-in types.

Reference​