Built-in Types¶
The following sections describe the standard types that are built into the interpreter.
The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions.
Some collection classes are mutable. The methods that add, subtract, or
rearrange their members in place, and don’t return a specific item, never return
the collection instance itself but None.
Some operations are supported by several object types; in particular,
practically all objects can be compared for equality, tested for truth
value, and converted to a string (with the repr() function or the
slightly different str() function). The latter function is implicitly
used when an object is written by the print() function.
Truth Value Testing¶
Any object can be tested for truth value, for use in an if or
while condition or as operand of the Boolean operations below.
By default, an object is considered true unless its class defines either a
__bool__() method that returns False or a
__len__() method that
returns zero, when called with the object. [1] Here are most of the built-in
objects considered false:
constants defined to be false:
NoneandFalsezero of any numeric type:
0,0.0,0j,Decimal(0),Fraction(0, 1)empty sequences and collections:
'',(),[],{},set(),range(0)
Operations and built-in functions that have a Boolean result always return 0
or False for false and 1 or True for true, unless otherwise stated.
(Important exception: the Boolean operations or and and always return
one of their operands.)
Boolean Operations — and, or, not¶
These are the Boolean operations, ordered by ascending priority:
Operation |
Result |
Notes |
|---|---|---|
|
if x is true, then x, else y |
(1) |
|
if x is false, then x, else y |
(2) |
|
if x is false, then |
(3) |
Notes:
This is a short-circuit operator, so it only evaluates the second argument if the first one is false.
This is a short-circuit operator, so it only evaluates the second argument if the first one is true.
nothas a lower priority than non-Boolean operators, sonot a == bis interpreted asnot (a == b), anda == not bis a syntax error.
Comparisons¶
There are eight comparison operations in Python. They all have the same
priority (which is higher than that of the Boolean operations). Comparisons can
be chained arbitrarily; for example, x < y <= z is equivalent to x < y and
y <= z, except that y is evaluated only once (but in both cases z is not
evaluated at all when x < y is found to be false).
This table summarizes the comparison operations:
Operation |
Meaning |
|---|---|
|
strictly less than |
|
less than or equal |
|
strictly greater than |
|
greater than or equal |
|
equal |
|
not equal |
|
object identity |
|
negated object identity |
Objects of different types, except different numeric types, never compare equal.
The == operator is always defined but for some object types (for example,
class objects) is equivalent to is. The <, <=, > and >=
operators are only defined where they make sense; for example, they raise a
TypeError exception when one of the arguments is a complex number.
Non-identical instances of a class normally compare as non-equal unless the
class defines the __eq__() method.
Instances of a class cannot be ordered with respect to other instances of the
same class, or other types of object, unless the class defines enough of the
methods __lt__(), __le__(), __gt__(), and
__ge__() (in general, __lt__() and
__eq__() are sufficient, if you want the conventional meanings of the
comparison operators).
The behavior of the is and is not operators cannot be
customized; also they can be applied to any two objects and never raise an
exception.
Two more operations with the same syntactic priority, in and
not in, are supported by types that are iterable or
implement the __contains__() method.
Numeric Types — int, float, complex¶
There are three distinct numeric types: integers, floating-point
numbers, and complex numbers. In addition, Booleans are a
subtype of integers. Integers have unlimited precision. Floating-point
numbers are usually implemented using double in C; information
about the precision and internal representation of floating-point
numbers for the machine on which your program is running is available
in sys.float_info. Complex numbers have a real and imaginary
part, which are each a floating-point number. To extract these parts
from a complex number z, use z.real and z.imag. (The standard
library includes the additional numeric types fractions.Fraction, for
rationals, and decimal.Decimal, for floating-point numbers with
user-definable precision.)
Numbers are created by numeric literals or as the result of built-in functions
and operators. Unadorned integer literals (including hex, octal and binary
numbers) yield integers. Numeric literals containing a decimal point or an
exponent sign yield floating-point numbers. Appending 'j' or 'J' to a
numeric literal yields an imaginary number (a complex number with a zero real
part) which you can add to an integer or float to get a complex number with real
and imaginary parts.
The constructors int(), float(), and
complex() can be used to produce numbers of a specific type.
Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the “narrower” type is widened to that of the other, where integer is narrower than floating point. Arithmetic with complex and real operands is defined by the usual mathematical formula, for example:
x + complex(u, v) = complex(x + u, v)
x * complex(u, v) = complex(x * u, x * v)
A comparison between numbers of different types behaves as though the exact values of those numbers were being compared. [2]
All numeric types (except complex) support the following operations (for priorities of the operations, see Operator precedence):
Operation |
Result |
Notes |
Full documentation |
|---|---|---|---|
|
sum of x and y |
||
|
difference of x and y |
||
|
product of x and y |
||
|
quotient of x and y |
||
|
floored quotient of x and y |
(1)(2) |
|
|
remainder of |
(2) |
|
|
x negated |
||
|
x unchanged |
||
|
absolute value or magnitude of x |
||
|
x converted to integer |
(3)(6) |
|
|
x converted to floating point |
(4)(6) |
|
|
a complex number with real part re, imaginary part im. im defaults to zero. |
(6) |
|
|
conjugate of the complex number c |
||
|
the pair |
(2) |
|
|
x to the power y |
(5) |
|
|
x to the power y |
(5) |
Notes:
Also referred to as integer division. For operands of type
int, the result has typeint. For operands of typefloat, the result has typefloat. In general, the result is a whole integer, though the result’s type is not necessarilyint. The result is always rounded towards minus infinity:1//2is0,(-1)//2is-1,1//(-2)is-1, and(-1)//(-2)is0.Not for complex numbers. Instead convert to floats using
abs()if appropriate.Conversion from
floattointtruncates, discarding the fractional part. See functionsmath.floor()andmath.ceil()for alternative conversions.float also accepts the strings “nan” and “inf” with an optional prefix “+” or “-” for Not a Number (NaN) and positive or negative infinity.
Python defines
pow(0, 0)and0 ** 0to be1, as is common for programming languages.The numeric literals accepted include the digits
0to9or any Unicode equivalent (code points with theNdproperty).See the Unicode Standard for a complete list of code points with the
Ndproperty.
All numbers.Real types (int and float) also include
the following operations:
Operation |
Result |
|---|---|
x truncated to |
|
x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0. |
|
the greatest |
|
the least |
For additional numeric operations see the math and cmath
modules.
Bitwise Operations on Integer Types¶
Bitwise operations only make sense for integers. The result of bitwise operations is calculated as though carried out in two’s complement with an infinite number of sign bits.
The priorities of the binary bitwise operations are all lower than the numeric
operations and higher than the comparisons; the unary operation ~ has the
same priority as the other unary numeric operations (+ and -).
This table lists the bitwise operations sorted in ascending priority:
Operation |
Result |
Notes |
|---|---|---|
|
bitwise or of x and y |
(4) |
|
bitwise exclusive or of x and y |
(4) |
|
bitwise and of x and y |
(4) |
|
x shifted left by n bits |
(1)(2) |
|
x shifted right by n bits |
(1)(3) |
|
the bits of x inverted |
Notes:
Negative shift counts are illegal and cause a
ValueErrorto be raised.A left shift by n bits is equivalent to multiplication by
pow(2, n).A right shift by n bits is equivalent to floor division by
pow(2, n).Performing these calculations with at least one extra sign extension bit in a finite two’s complement representation (a working bit-width of
1 + max(x.bit_length(), y.bit_length())or more) is sufficient to get the same result as if there were an infinite number of sign bits.
Additional Methods on Integer Types¶
The int type implements the numbers.Integral abstract base
class. In addition, it provides a few more methods:
- int.bit_length()¶
Return the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros:
>>> n = -37 >>> bin(n) '-0b100101' >>> n.bit_length() 6
More precisely, if
xis nonzero, thenx.bit_length()is the unique positive integerksuch that2**(k-1) <= abs(x) < 2**k. Equivalently, whenabs(x)is small enough to have a correctly rounded logarithm, thenk = 1 + int(log(abs(x), 2)). Ifxis zero, thenx.bit_length()returns0.Equivalent to:
def bit_length(self): s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = s.lstrip('-0b') # remove leading zeros and minus sign return len(s) # len('100101') --> 6
Added in version 3.1.
- int.bit_count()¶
Return the number of ones in the binary representation of the absolute value of the integer. This is also known as the population count. Example:
>>> n = 19 >>> bin(n) '0b10011' >>> n.bit_count() 3 >>> (-n).bit_count() 3
Equivalent to:
def bit_count(self): return bin(self).count("1")
Added in version 3.10.
- int.to_bytes(length=1, byteorder='big', *, signed=False)¶
Return an array of bytes representing an integer.
>>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03'
The integer is represented using length bytes, and defaults to 1. An
OverflowErroris raised if the integer is not representable with the given number of bytes.The byteorder argument determines the byte order used to represent the integer, and defaults to
"big". If byteorder is"big", the most significant byte is at the beginning of the byte array. If byteorder is"little", the most significant byte is at the end of the byte array.The signed argument determines whether two’s complement is used to represent the integer. If signed is
Falseand a negative integer is given, anOverflowErroris raised. The default value for signed isFalse.The default values can be used to conveniently turn an integer into a single byte object:
>>> (65).to_bytes() b'A'
However, when using the default arguments, don’t try to convert a value greater than 255 or you’ll get an
OverflowError.Equivalent to:
def to_bytes(n, length=1, byteorder='big', signed=False): if byteorder == 'little': order = range(length) elif byteorder == 'big': order = reversed(range(length)) else: raise ValueError("byteorder must be either 'little' or 'big'") return bytes((n >> i*8) & 0xff for i in order)
Added in version 3.2.
Changed in version 3.11: Added default argument values for
lengthandbyteorder.
- classmethod int.from_bytes(bytes, byteorder='big', *, signed=False)¶
Return the integer represented by the given array of bytes.
>>> int.from_bytes(b'\x00\x10', byteorder='big') 16 >>> int.from_bytes(b'\x00\x10', byteorder='little') 4096 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) -1024 >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False) 64512 >>> int.from_bytes([255, 0, 0], byteorder='big') 16711680
The argument bytes must either be a bytes-like object or an iterable producing bytes.
The byteorder argument determines the byte order used to represent the integer, and defaults to
"big". If byteorder is"big", the most significant byte is at the beginning of the byte array. If byteorder is"little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, usesys.byteorderas the byte order value.The signed argument indicates whether two’s complement is used to represent the integer.
Equivalent to:
def from_bytes(bytes, byteorder='big', signed=False): if byteorder == 'little': little_ordered = list(bytes) elif byteorder == 'big': little_ordered = list(reversed(bytes)) else: raise ValueError("byteorder must be either 'little' or 'big'") n = sum(b << i*8 for i, b in enumerate(little_ordered)) if signed and little_ordered and (little_ordered[-1] & 0x80): n -= 1 << 8*len(little_ordered) return n
Added in version 3.2.
Changed in version 3.11: Added default argument value for
byteorder.
- int.as_integer_ratio()¶
Return a pair of integers whose ratio is equal to the original integer and has a positive denominator. The integer ratio of integers (whole numbers) is always the integer as the numerator and
1as the denominator.Added in version 3.8.
- int.is_integer()¶
Returns
True. Exists for duck type compatibility withfloat.is_integer().Added in version 3.12.
Additional Methods on Float¶
The float type implements the numbers.Real abstract base
class. float also has the following additional methods.
- classmethod float.from_number(x)¶
Class method to return a floating-point number constructed from a number x.
If the argument is an integer or a floating-point number, a floating-point number with the same value (within Python’s floating-point precision) is returned. If the argument is outside the range of a Python float, an
OverflowErrorwill be raised.For a general Python object
x,float.from_number(x)delegates tox.__float__(). If__float__()is not defined then it falls back to__index__().Added in version 3.14.
- float.as_integer_ratio()¶
Return a pair of integers whose ratio is exactly equal to the original float. The ratio is in lowest terms and has a positive denominator. Raises
OverflowErroron infinities and aValueErroron NaNs.
- float.is_integer()¶
Return
Trueif the float instance is finite with integral value, andFalseotherwise:>>> (-2.0).is_integer() True >>> (3.2).is_integer() False
Two methods support conversion to and from hexadecimal strings. Since Python’s floats are stored internally as binary numbers, converting a float to or from a decimal string usually involves a small rounding error. In contrast, hexadecimal strings allow exact representation and specification of floating-point numbers. This can be useful when debugging, and in numerical work.
- float.hex()¶
Return a representation of a floating-point number as a hexadecimal string. For finite floating-point numbers, this representation will always include a leading
0xand a trailingpand exponent.
- classmethod float.fromhex(s)¶
Class method to return the float represented by a hexadecimal string s. The string s may have leading and trailing whitespace.
Note that float.hex() is an instance method, while
float.fromhex() is a class method.
A hexadecimal string takes the form:
[sign] ['0x'] integer ['.' fraction] ['p' exponent]
where the optional sign may by either + or -, integer
and fraction are strings of hexadecimal digits, and exponent
is a decimal integer with an optional leading sign. Case is not
significant, and there must be at least one hexadecimal digit in
either the integer or the fraction. This syntax is similar to the
syntax specified in section 6.4.4.2 of the C99 standard, and also to
the syntax used in Java 1.5 onwards. In particular, the output of
float.hex() is usable as a hexadecimal floating-point literal in
C or Java code, and hexadecimal strings produced by C’s %a format
character or Java’s Double.toHexString are accepted by
float.fromhex().
Note that the exponent is written in decimal rather than hexadecimal,
and that it gives the power of 2 by which to multiply the coefficient.
For example, the hexadecimal string 0x3.a7p10 represents the
floating-point number (3 + 10./16 + 7./16**2) * 2.0**10, or
3740.0:
>>> float.fromhex('0x3.a7p10')
3740.0
Applying the reverse conversion to 3740.0 gives a different
hexadecimal string representing the same number:
>>> float.hex(3740.0)
'0x1.d380000000000p+11'
Additional Methods on Complex¶
The complex type implements the numbers.Complex
abstract base class.
complex also has the following additional methods.
- classmethod complex.from_number(x)¶
Class method to convert a number to a complex number.
For a general Python object
x,complex.from_number(x)delegates tox.__complex__(). If__complex__()is not defined then it falls back to__float__(). If__float__()is not defined then it falls back to__index__().Added in version 3.14.
Hashing of numeric types¶
For numbers x and y, possibly of different types, it’s a requirement
that hash(x) == hash(y) whenever x == y (see the __hash__()
method documentation for more details). For ease of implementation and
efficiency across a variety of numeric types (including int,
float, decimal.Decimal and fractions.Fraction)
Python’s hash for numeric types is based on a single mathematical function
that’s defined for any rational number, and hence applies to all instances of
int and fractions.Fraction, and all finite instances of
float and decimal.Decimal. Essentially, this function is
given by reduction modulo P for a fixed prime P. The value of P is
made available to Python as the modulus attribute of
sys.hash_info.
CPython implementation detail: Currently, the prime used is P = 2**31 - 1 on machines with 32-bit C
longs and P = 2**61 - 1 on machines with 64-bit C longs.
Here are the rules in detail:
If
x = m / nis a nonnegative rational number andnis not divisible byP, definehash(x)asm * invmod(n, P) % P, whereinvmod(n, P)gives the inverse ofnmoduloP.If
x = m / nis a nonnegative rational number andnis divisible byP(butmis not) thennhas no inverse moduloPand the rule above doesn’t apply; in this case definehash(x)to be the constant valuesys.hash_info.inf.If
x = m / nis a negative rational number definehash(x)as-hash(-x). If the resulting hash is-1, replace it with-2.The particular values
sys.hash_info.infand-sys.hash_info.infare used as hash values for positive infinity or negative infinity (respectively).For a
complexnumberz, the hash values of the real and imaginary parts are combined by computinghash(z.real) + sys.hash_info.imag * hash(z.imag), reduced modulo2**sys.hash_info.widthso that it lies inrange(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width - 1)). Again, if the result is-1, it’s replaced with-2.
To clarify the above rules, here’s some example Python code,
equivalent to the built-in hash, for computing the hash of a rational
number, float, or complex:
import sys, math
def hash_fraction(m, n):
"""Compute the hash of a rational number m / n.
Assumes m and n are integers, with n positive.
Equivalent to hash(fractions.Fraction(m, n)).
"""
P = sys.hash_info.modulus
# Remove common factors of P. (Unnecessary if m and n already coprime.)
while m % P == n % P == 0:
m, n = m // P, n // P
if n % P == 0:
hash_value = sys.hash_info.inf
else:
# Fermat's Little Theorem: pow(n, P-1, P) is 1, so
# pow(n, P-2, P) gives the inverse of n modulo P.
hash_value = (abs(m) % P) * pow(n, P - 2, P) % P
if m < 0:
hash_value = -hash_value
if hash_value == -1:
hash_value = -2
return hash_value
def hash_float(x):
"""Compute the hash of a float x."""
if math.isnan(x):
return object.__hash__(x)
elif math.isinf(x):
return sys.hash_info.inf if x > 0 else -sys.hash_info.inf
else:
return hash_fraction(*x.as_integer_ratio())
def hash_complex(z):
"""Compute the hash of a complex number z."""
hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag)
# do a signed reduction modulo 2**sys.hash_info.width
M = 2**(sys.hash_info.width - 1)
hash_value = (hash_value & (M - 1)) - (hash_value & M)
if hash_value == -1:
hash_value = -2
return hash_value
Boolean Type - bool¶
Booleans represent truth values. The bool type has exactly two
constant instances: True and False.
The built-in function bool() converts any value to a boolean, if the
value can be interpreted as a truth value (see section Truth Value Testing above).
For logical operations, use the boolean operators and,
or and not.
When applying the bitwise operators &, |, ^ to two booleans, they
return a bool equivalent to the logical operations “and”, “or”, “xor”. However,
the logical operators and, or and != should be preferred
over &, | and ^.
Deprecated since version 3.12: The use of the bitwise inversion operator ~ is deprecated and will
raise an error in Python 3.16.
bool is a subclass of int (see Numeric Types — int, float, complex). In
many numeric contexts, False and True behave like the integers 0 and 1, respectively.
However, relying on this is discouraged; explicitly convert using int()
instead.
Iterator Types¶
Python supports a concept of iteration over containers. This is implemented using two distinct methods; these are used to allow user-defined classes to support iteration. Sequences, described below in more detail, always support the iteration methods.
One method needs to be defined for container objects to provide iterable support:
- container.__iter__()¶
Return an iterator object. The object is required to support the iterator protocol described below. If a container supports different types of iteration, additional methods can be provided to specifically request iterators for those iteration types. (An example of an object supporting multiple forms of iteration would be a tree structure which supports both breadth-first and depth-first traversal.) This method corresponds to the
tp_iterslot of the type structure for Python objects in the Python/C API.
The iterator objects themselves are required to support the following two methods, which together form the iterator protocol:
- iterator.__iter__()¶
Return the iterator object itself. This is required to allow both containers and iterators to be used with the
forandinstatements. This method corresponds to thetp_iterslot of the type structure for Python objects in the Python/C API.
- iterator.__next__()¶
Return the next item from the iterator. If there are no further items, raise the
StopIterationexception. This method corresponds to thetp_iternextslot of the type structure for Python objects in the Python/C API.
Python defines several iterator objects to support iteration over general and specific sequence types, dictionaries, and other more specialized forms. The specific types are not important beyond their implementation of the iterator protocol.
Once an iterator’s __next__() method raises
StopIteration, it must continue to do so on subsequent calls.
Implementations that do not obey this property are deemed broken.
Generator Types¶
Python’s generators provide a convenient way to implement the iterator
protocol. If a container object’s __iter__() method is implemented as a
generator, it will automatically return an iterator object (technically, a
generator object) supplying the __iter__() and __next__()
methods.
More information about generators can be found in the documentation for
the yield expression.
Sequence Types — list, tuple, range¶
There are three basic sequence types: lists, tuples, and range objects. Additional sequence types tailored for processing of binary data and text strings are described in dedicated sections.
Common Sequence Operations¶
The operations in the following table are supported by most sequence types,
both mutable and immutable. The collections.abc.Sequence ABC is
provided to make it easier to correctly implement these operations on
custom sequence types.
This table lists the sequence operations sorted in ascending priority. In the table, s and t are sequences of the same type, n, i, j and k are integers and x is an arbitrary object that meets any type and value restrictions imposed by s.
The in and not in operations have the same priorities as the
comparison operations. The + (concatenation) and * (repetition)
operations have the same priority as the corresponding numeric operations. [3]
Operation |
Result |
Notes |
|---|---|---|
|
|
(1) |
|
|
(1) |
|
the concatenation of s and t |
(6)(7) |
|
equivalent to adding s to itself n times |
(2)(7) |
|
ith item of s, origin 0 |
(3)(8) |
|
slice of s from i to j |
(3)(4) |
|
slice of s from i to j with step k |
(3)(5) |
|
length of s |
|
|
smallest item of s |
|
|
largest item of s |
Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length. (For full details see Comparisons in the language reference.)
Forward and reversed iterators over mutable sequences access values using an
index. That index will continue to march forward (or backward) even if the
underlying sequence is mutated. The iterator terminates only when an
IndexError or a StopIteration is encountered (or when the index
drops below zero).
Notes:
While the
inandnot inoperations are used only for simple containment testing in the general case, some specialised sequences (such asstr,bytesandbytearray) also use them for subsequence testing:>>> "gg" in "eggs" True
Values of n less than
0are treated as0(which yields an empty sequence of the same type as s). Note that items in the sequence s are not copied; they are referenced multiple times. This often haunts new Python programmers; consider:>>> lists = [[]] * 3 >>> lists [[], [], []] >>> lists[0].append(3) >>> lists [[3], [3], [3]]
What has happened is that
[[]]is a one-element list containing an empty list, so all three elements of[[]] * 3are references to this single empty list. Modifying any of the elements oflistsmodifies this single list. You can create a list of different lists this way:>>> lists = [[] for i in range(3)] >>> lists[0].append(3) >>> lists[1].append(5) >>> lists[2].append(7) >>> lists [[3], [5], [7]]
Further explanation is available in the FAQ entry How do I create a multidimensional list?.
If i or j is negative, the index is relative to the end of sequence s:
len(s) + iorlen(s) + jis substituted. But note that-0is still0.The slice of s from i to j is defined as the sequence of items with index k such that
i <= k < j. If i or j is greater thanlen(s), uselen(s). If i is omitted orNone, use0. If j is omitted orNone, uselen(s). If i is greater than or equal to j, the slice is empty.The slice of s from i to j with step k is defined as the sequence of items with index
x = i + n*ksuch that0 <= n < (j-i)/k. In other words, the indices arei,i+k,i+2*k,i+3*kand so on, stopping when j is reached (but never including j). When k is positive, i and j are reduced tolen(s)if they are greater. When k is negative, i and j are reduced tolen(s) - 1if they are greater. If i or j are omitted orNone, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k isNone, it is treated like1.Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost, you must switch to one of the alternatives below:
if concatenating
strobjects, you can build a list and usestr.join()at the end or else write to anio.StringIOinstance and retrieve its value when completeif concatenating
bytesobjects, you can similarly usebytes.join()orio.BytesIO, or you can do in-place concatenation with a