Python is dynamically typed. Names have no type; each object does. The language does not convert between types unless the operation says so, and arithmetic on mixed numbers is the main case. This page describes the behaviour of the built-in types. Their place in the language is on the Data model page. The source forms of literals are on Lexical structure.
Numbers
| Type | Holds | Range |
|---|---|---|
int | Whole numbers | Unlimited, bounded only by memory |
bool | True and False | Subtype of int, equal to 1 and 0 |
float | Floating-point numbers | IEEE 754 double in CPython: largest finite is about 1.8e308 |
complex | A pair of floats, .real and .imag | As for float |
In a binary operation between different numeric types the arguments are converted to
a common type (6.1): if either is complex, the other becomes
complex; otherwise if either is float, the other becomes
float. The standard library adds decimal.Decimal and
fractions.Fraction.
Arithmetic
| Operation | Result |
|---|---|
x + y, x - y, x * y | Sum, difference, product |
x / y | Division. Always a float for int operands (PEP 238) |
x // y | Floored quotient: rounds toward minus infinity |
x % y | Remainder, with the sign of y |
divmod(x, y) | The pair (x // y, x % y) |
x ** y, pow(x, y) | Power. 0 ** 0 is 1 |
pow(x, y, m) | Modular power; a negative y gives a modular inverse (3.8) |
-x, +x, abs(x) | Negated, unchanged, absolute value |
7 / 2 # 3.5
7 // 2 # 3
-7 // 2 # -4: rounds down, not toward zero
-7 % 3 # 2: sign of the right operand
7 % -3 # -2
divmod(-7, 3) # (-3, 2)
7.5 // 2 # 3.0
2 ** -1 # 0.5
-2 ** 2 # -4: ** binds tighter than unary minus
round(2.5) # 2: rounds half to even
round(3.5) # 4
Integers
int has unlimited precision. There is no overflow and no separate long
type. Bitwise operators treat a negative number as if it were an infinite two's
complement value, so ~x is -x - 1. A shift by a negative
count raises ValueError.
| Method | Result |
|---|---|
x.bit_length() | Bits needed, leaving out the sign |
x.bit_count() | Number of ones in the binary form of abs(x) (3.10) |
x.to_bytes(length=1, byteorder='big', *, signed=False) | The value as bytes |
int.from_bytes(b, byteorder='big', *, signed=False) | The value of bytes |
x.as_integer_ratio() | The pair (x, 1) |
x.is_integer() | Always True (3.12) |
Conversion between int and str in a base that is not a
power of two raises ValueError if the number has more than 4300 digits,
a limit added against denial-of-service attacks (Python 3.11). The limit can be set
or removed with sys.set_int_max_str_digits(). A non-zero limit cannot
be below 640.
Booleans
bool is a subclass of int that cannot be subclassed
further, so True + True is 2. True and False
are keywords. ~True is -2, which has been deprecated since Python 3.12:
use not x for logic. Truth values are below.
Floats
- Most decimal fractions have no exact binary form:
0.1 + 0.2is0.30000000000000004. Usemath.iscloseto compare, orDecimalfor exact decimal arithmetic. float("inf")andfloat("nan")make the special values. NaN is not equal to anything, including itself.sys.float_infogives the limits of the type.x.is_integer(),x.as_integer_ratio(),x.hex()andfloat.fromhex(s)give exact forms.
Complex numbers
A complex value has .real and .imag
attributes and a conjugate() method, and abs(c) gives its
magnitude. //, % and divmod are not defined,
and complex numbers cannot be ordered with <. The
cmath module has the complex versions of the maths functions.
Sequences
A sequence is an ordered collection indexed by integers from 0.
| Type | Items | Mutable? | Written as |
|---|---|---|---|
list | Any objects | Yes | [1, 2], [] |
tuple | Any objects | No | (1, 2), (1,), () |
range | Integers, computed on demand | No | range(10) |
str | Unicode code points | No | "text" |
bytes | Integers 0 to 255 | No | b"data" |
bytearray | Integers 0 to 255 | Yes | bytearray(b"data") |
memoryview | A view of another object's bytes | Per the source | memoryview(obj) |
Common operations
| Operation | Result |
|---|---|
x in s, x not in s | Membership. For str and bytes, a substring test |
s + t | Concatenation, into a new sequence |
s * n | n repetitions. A negative n counts as 0 |
s[i] | Item i. A negative index counts from the end |
s[i:j], s[i:j:k] | A slice. Indices beyond the ends are clipped |
len(s), min(s), max(s) | Length, smallest, largest |
s.count(x), s.index(x[, i[, j]]) | Occurrences, and the first index. index raises ValueError if absent |
s = [0, 1, 2, 3, 4]
s[-1] # 4
s[1:3] # [1, 2]
s[:2] # [0, 1]
s[::2] # [0, 2, 4]
s[::-1] # [4, 3, 2, 1, 0]
s[10:20] # []
lists = [[]] * 3 # three references to the one inner list
lists[0].append(1)
lists # [[1], [1], [1]]
Mutable sequences
| Operation | Effect |
|---|---|
s[i] = x, s[i:j] = t, s[i:j:k] = t | Replace an item or a slice. An extended slice must match in length |
del s[i], del s[i:j] | Remove items |
s.append(x), s.extend(t), s += t | Add one item, or all of an iterable |
s.insert(i, x) | Insert before position i |
s.pop([i]) | Remove and return an item (the last by default) |
s.remove(x) | Remove the first x; ValueError if absent |
s.clear(), s.copy(), s.reverse() | Empty it, make a shallow copy, reverse in place |
s.sort(*, key=None, reverse=False) | Lists only. A stable in-place sort using < |
Methods that change a sequence in place return None.
sorted(iterable) returns a new list.
Tuples and ranges
A tuple is written by its commas, not its brackets: 1, 2 is a tuple,
and a tuple of one needs a trailing comma: (1,). It is hashable when
all its items are.
A range stores only its start, stop and step, and computes the items.
range(5) is 0 to 4, and range(1, 10, 2) is 1, 3, 5, 7, 9.
Membership is constant time, x in range(...). A step of 0 raises
ValueError.
Text and binary
str is a sequence of Unicode code points, and a one-character string
is the only character type. Indexing returns a string of length 1.
bytes and bytearray index to integers, so
b"A"[0] is 65. Encoding and decoding go between them:
"café".encode("utf-8") # b'caf\xc3\xa9'
b'caf\xc3\xa9'.decode() # 'café'
", ".join(["a", "b"]) # 'a, b'
str.encode and bytes.decode default to UTF-8Mixing str and bytes in an operation raises
TypeError. Building a long string in a loop is quadratic, so join a list
instead. removeprefix and removesuffix remove a fixed
affix (3.9, PEP 616); strip removes any of a set of characters.
memoryview(b) exposes an object's bytes without copying them.
Mappings
A mapping connects hashable keys to values.
| Type | Mutable? | Written as |
|---|---|---|
dict | Yes | {"a": 1}, dict(a=1) |
frozendict | No (3.15, PEP 814) | frozendict(a=1) |
- A dictionary keeps its items in insertion order, a language guarantee since Python 3.7. Updating an existing key keeps its position.
- Keys are compared by value, so
1,1.0andTrueare the same key. d[k]raisesKeyErrorif absent.d.get(k, default)does not.d.keys(),d.values()andd.items()are views that follow later changes. Keys and items views support set operations.d | emerges, with the right side winning, andd |= eupdates in place (3.9, PEP 584).d.popitem()removes the most recently added item.
A frozendict inherits directly from object, keeps insertion
order, and is hashable if all its keys and values are. |= makes a new
one. Its equality ignores order, as for dict.
Sets
set and the immutable, hashable frozenset hold unique
hashable items with no order. {} is an empty dictionary, so an empty set
is set().
| Operator | Method | Result |
|---|---|---|
a | b | a.union(b) | In either |
a & b | a.intersection(b) | In both |
a - b | a.difference(b) | In a only |
a ^ b | a.symmetric_difference(b) | In exactly one |
a <= b, a < b | a.issubset(b) | Subset, proper subset |
a >= b, a > b | a.issuperset(b) | Superset, proper superset |
The operators require sets, and the methods accept any iterable. Sets add
add, remove (raises KeyError),
discard (does not) and pop. The comparison operators form a
partial order, so sorting a list of sets is undefined.
None, NotImplemented and Ellipsis
| Object | Type | Use |
|---|---|---|
None | types.NoneType | The absence of a value. Compare with is None. It is false |
NotImplemented | types.NotImplementedType | Returned by a special method that cannot handle its operand. Using it as a truth value raises TypeError since 3.14 |
Ellipsis, ... | types.EllipsisType | Used in subscripts and in stubs. It is true |
Python 3.15 adds the built-in sentinel(name) for a program's own unique
marker values (PEP 661). Sentinels are true and are compared with is.
Truth values
Any object can be tested in if, while or a Boolean
operation. An object is true unless it fits one of these rules:
| False values |
|---|
None and False |
Zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1) |
Empty sequences and collections: '', (), [], {}, set(), range(0) |
Objects whose __bool__ returns False, or whose __len__ returns 0 |
The Boolean operators return one of their operands, not a bool (see
Boolean operations).
not does return a bool.
Conversions
Conversion is explicit: "3" + 4 raises TypeError. The type
names act as conversion functions.
| Call | Result |
|---|---|
int(x) | From a number, truncating toward zero; from a string with optional spaces, sign and _ |
int(s, base) | Base 2 to 36, or 0 to take the base from a prefix |
float(x) | From a number or a string, including 'inf' and 'nan' |
complex(s), complex(re, im) | From a string like '1+2j', or two numbers |
bool(x) | The truth value of x |
str(x) | The text form, using __str__ |
str(b, encoding), bytes(s, encoding) | Decode, encode |
repr(x), ascii(x) | The developer form; ascii also escapes non-ASCII |
bytes(n), bytes(iterable) | n zero bytes, or integers from 0 to 255 |
list(it), tuple(it), set(it), frozenset(it) | Collect an iterable |
dict(pairs), dict(**kw), dict(mapping) | Build a dictionary |
chr(n), ord(c) | Code point to character, and back |
hex(n), oct(n), bin(n) | A string with 0x, 0o or 0b |
format(x, spec) | Formatted text, by __format__ |
int("ff", 16) # 255
int("0b101", 0) # 5
int(3.9) # 3
int(-3.9) # -3
float("1e3") # 1000.0
str(1.0) # '1.0'
list("ab") # ['a', 'b']
dict([("a", 1)]) # {'a': 1}
bool("False") # True: any non-empty string is true