Language
Data types
Type checks
<class 'int'> <class 'float'> <class 'str'> <class 'list'> <class 'tuple'> <class 'set'> <class 'dict'> <class 'NoneType'> <class 'bool'>
Use isinstance to test whether a value belongs to a type. Constructors such as int, float, str, bool, list, tuple and set double as converters. Builtins lists every conversion.
int(3.7) is 3 and int(-3.7) is -3. The conversion truncates toward zero and never rounds.
Integer
There is one int type with a signed 128-bit range, from -(2**127) to 2**127 - 1. Going out of range raises OverflowError. Limits and errors has the details.
There is no complex type.
170141183460469231731687303715884105727 overflow
Float
Floats are IEEE-754 doubles. Mixing int and float in arithmetic yields a float.
False True 5.0
round rounds ties to even, see Builtins.
Boolean
bool has two values, True and False. It is a subclass of int. Truthy and falsy lists which values count as true.
True 2
String
A string is an immutable sequence of Unicode code points.
- Indexing returns a one-character string.
lencounts code points, not bytes.- Iteration yields characters.
h o éll 5 héllo world héllohéllo True
Syntax covers quotes and escapes. Methods lists the methods.
Bytes
bytes is an immutable sequence of octets, each 0 to 255. It stores raw data, not text. Indexing returns an int, and iteration yields ints.
b'hello' 5 104 b'ell' 97 98 99
bytes never equals str, even for valid UTF-8. Non-ASCII characters in a bytes literal are stored as their UTF-8 encoding.
False b'\xc3\xa9'
Encoding round-trips use str.encode and bytes.decode.
b'Edge Python' Edge Python
Builtins lists the constructor forms, such as bytes(n) and bytes from an int iterable. Methods covers hex, split, fromhex and the rest.
List
A list is a mutable sequence. Assignment copies the reference. Aliases share mutations.
[99, 2, 3, 4] 4 [99, 2, 3, 4, 5]
Equality is structural.
True True
Slices change a list in place.
- Slice assignment with step 1 resizes the list.
- Slice deletion removes a range.
- Assigning into an empty slice inserts.
[1, 20, 30, 40, 4, 5] [1, 20, 4, 5] [1, 99, 20, 4, 5]
+= on a list extends it in place. Aliases see the change.
[1, 2, 3, 4]
Tuple
A tuple is an immutable sequence. It is hashable when its elements are. That makes it the usual compound dict key.
1 (1, 2, 3, 4, 5) key
Syntax covers literal forms such as the trailing comma in (1,).
Dict
A dict is a mapping that keeps insertion order.
- Keys must be hashable. Numbers, strings, bytes, bools,
None, frozensets and tuples of hashables qualify. - An unhashable key raises
TypeError. - Numerically equal keys collapse.
1,1.0andTrueare one key, and the latest assignment wins. - Iteration yields keys.
1
{'a': 1, 'b': 2, 'c': 3}
{1: 'bool'}
x
yunhashable key
Methods covers keys, values, items, get and the rest.
Set
A set is an unordered collection of unique, hashable values.
|,&,-and^build new sets.|=,&=and^=update the set in place. Aliases observe the change.<=and<test subsets.
4 [1, 2, 3, 4] [1, 2, 3, 4] [2, 3] True [1, 2, 3, 4, 5]
Syntax shows how to write an empty set. Methods covers named operations such as union and issubset.
Frozenset
A frozenset is an immutable, hashable set built with frozenset(iterable).
- It supports
len, iteration, membership, unpacking, the algebra operators and the subset comparisons. - In mixed
setandfrozensetalgebra the result takes the type of the left operand. - It has no named methods.
frozenset({1}).union({2})raisesAttributeError. Convert withset(fs)for the method API.
3 True [1, 2, 3] <class 'frozenset'> <class 'set'> [1, 2, 3, 4] True ok
Range
A range is a lazy integer sequence, built with range(stop), range(start, stop) or range(start, stop, step). Builtins has examples.
None and Ellipsis
None is the only value of NoneType. Test for it with is None.
... is the only value of type ellipsis. It compares equal only to itself and is distinct from the string '...'.
Ellipsis True <class 'ellipsis'> False
Generic aliases
Type parameters, aliases and unions exist at runtime as small values. None of them checks a type.
list[int]is a generic alias. It prints aslist[int]and calling it builds a plainlist.class Box[T]keeps its parameters in__type_params__, andBox[int]is a generic alias.- On a class that defines
__class_getitem__,C[x]calls it. def f[T]parses its type parameters and discards them.type X = vbinds a lazy alias.X.__value__evaluatesvwhen read.int | Noneis a union thatisinstanceaccepts.
(T,) 3 list[int] ['a', 'b'] tuple[int, int] True
Truthy and falsy
These values are falsy. Everything else is truthy.
| Falsy values |
|---|
None |
False |
0, 0.0 |
"", b"" |
[], () |
{}, set(), frozenset() |
range(0) |
False False False False True True
Behavioral notes
- Set iteration and
reprorder. Sets store elements in a hash table. Iteration andreprfollow hash order, not insertion order. Sort a set when the order matters. - Every NaN is one value. A NaN is found in a list holding another NaN, and a set keeps a single one, where CPython keeps one per object. Memory model explains why.
{3, 2, 1}
True 1 False