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