Skip to Content
LanguageData Types

Type checks

print(type(42)) print(type(3.14)) print(type("hi")) print(type([1, 2])) print(type((1, 2))) print(type({1, 2})) print(type({"a": 1})) print(type(None)) print(type(True))
Output · expected
<class 'int'> <class 'float'> <class 'str'> <class 'list'> <class 'tuple'> <class 'set'> <class 'dict'> <class 'NoneType'> <class 'bool'>

For runtime membership in a type, use isinstance.

Integer

One int type, transparently two-tier. A fast inline path auto-promotes to wide integers, capped at ±2¹²⁷ (full mechanics in Integer width). No CPython unbounded ints. No complex (1j, 2+3j).

# Modular exponentiation print(pow(7, 13, 19)) print(divmod(17, 5))
Output · expected
7 (3, 2)

Float

IEEE-754 double precision. Mixed arithmetic with int coerces to float.

print(0.1 + 0.2 == 0.3) print(-0.0 == 0.0) print(1 / 3) print(round(2.5)) # banker's rounding print(round(0.5)) print(round(1.55, 1))
Output · expected
False True 0.3333333333333333 2 0 1.6

String

Strings are immutable. Indexing returns a single-character string.

s = "hello" print(s[0], s[-1]) print(s[1:4]) print(len(s)) print(s + " world") print(s * 2) print("ll" in s)
Output · expected
h o ell 5 hello world hellohello True

Iteration yields characters:

for ch in "abc": print(ch)
Output · expected
a b c

len(s) and padding (str.center / str.zfill) measure in code points, not bytes. 'ñ'.center(5, '*') -> '**ñ**' (5 visual chars).

Bytes

Immutable sequence of bytes (each 0-255). Distinct from str: it stores raw octets, not Unicode. Indexing returns an int, not a single-byte slice.

data = b"hello" print(data) print(type(data)) print(len(data)) print(data[0]) # int, the byte value print(data[1:4]) # bytes, slice
Output · expected
b'hello' <class 'bytes'> 5 104 b'ell'
# Hex escapes for arbitrary bytes raw = b"\x00\x01\xff" print(raw) print(raw.hex())
Output · expected
b'\x00\x01\xff' 0001ff
# Iteration yields ints, not bytes for byte in b"abc": print(byte)
Output · expected
97 98 99
# Constructors print(bytes()) # empty print(bytes(3)) # zero-filled, length 3 print(bytes([65, 66, 67])) # from int iterable print(bytes("hi", "utf-8")) # encoded string
Output · expected
b'' b'\x00\x00\x00' b'ABC' b'hi'
# Round-tripping with str s = "Edge Python" encoded = s.encode("utf-8") decoded = encoded.decode("utf-8") print(encoded, decoded)
Output · expected
b'Edge Python' Edge Python

bytes is hashable and comparable to other bytes. bytes == str is always False, even for valid UTF-8. Methods include decode, hex, find, count, replace, split, startswith, endswith, lower, upper, strip, join, and the bytes.fromhex classmethod (see Methods). Encodings: "utf-8" (default), "ascii".

List

Mutable sequence.

xs = [1, 2, 3] xs[0] = 99 xs.append(4) print(xs) print(len(xs)) # Aliasing, both names see mutation ys = xs ys.append(5) print(xs)
Output · expected
[99, 2, 3, 4] 4 [99, 2, 3, 4, 5]
# Equality is structural print([1, 2, 3] == [1, 2, 3]) print([1, [2, 3]] == [1, [2, 3]])
Output · expected
True True
# Slice assignment (step=1) resizes the list in place xs = [1, 2, 3, 4, 5] xs[1:3] = [20, 30, 40] print(xs) # Slice deletion del xs[2:4] print(xs) # Insertion via empty slice xs[1:1] = [99] print(xs)
Output · expected
[1, 20, 30, 40, 4, 5] [1, 20, 4, 5] [1, 99, 20, 4, 5]

+= on a list extends in place, so aliases see it:

xs = [1, 2, 3] ys = xs xs += [4] print(ys)
Output · expected
[1, 2, 3, 4]

Tuple

Immutable sequence. It is the fastest container for fixed-size data. It is also the usual hashable container for compound dict keys (frozensets also work).

t = (1, 2, 3) print(t[0]) print(t + (4, 5)) print((1,)) # one-element needs trailing comma print(()) # empty
Output · expected
1 (1, 2, 3, 4, 5) (1,) ()

Dict

Insertion-ordered mapping. Keys must be hashable: numbers, strings, bytes, bools, None, frozensets, tuples of hashables. Mutable containers as keys -> TypeError: unhashable type. Numerically equal keys (1/1.0, True/1) collapse. The second insertion overwrites.

d = {"a": 1, "b": 2} print(d["a"]) d["c"] = 3 print(d) print(list(d.keys())) print(list(d.values())) print(list(d.items()))
Output · expected
1 {'a': 1, 'b': 2, 'c': 3} ['a', 'b', 'c'] [1, 2, 3] [('a', 1), ('b', 2), ('c', 3)]
# Iteration yields keys for k in {"x": 1, "y": 2}: print(k)
Output · expected
x y

Set

Unordered, no duplicates, hashable values. Mutators (add, remove, discard, pop, clear, update) and algebraic operators (|, &, -, ^ and named methods). See Methods.

s = {1, 2, 2, 3} s.add(4) print(s) print(len(s)) # Empty set literal is set(), not {} print(set()) print(type({})) # this is a dict # Algebra print({1, 2, 3} | {3, 4}) print({1, 2, 3} & {2, 3, 4}) print({1, 2} <= {1, 2, 3}) # subset
Output · expected
{2, 3, 4, 1} 4 set() <class 'dict'> {3, 1, 4, 2} {3, 2} True

Frozenset

Immutable, hashable set. Build with frozenset(iterable). Supports len, iteration, membership (in), tuple-unpacking (a, b = fs), the algebra operators | & - ^, the subset/superset comparisons < <= > >= == !=, and use as a dict key or set element. In mixed set / frozenset algebra the result takes the left operand’s type (frozenset | set is a frozenset, set | frozenset is a set).

It has no methods: the named set operations (union, intersection, difference, symmetric_difference, issubset, issuperset, isdisjoint) and copy raise AttributeError. Use the operators, or convert with set(fs) for the named-method / mutating API.

fs = frozenset({1, 2, 3}) print(len(fs)) print(2 in fs) a, b, c = fs # tuple-unpacking print(sorted([a, b, c])) # Operators yield a set; the result type follows the left operand (see above). print(sorted(fs | frozenset({4}))) print(sorted(fs - frozenset({1}))) print(fs <= frozenset({1, 2, 3, 4})) # subset print({fs: "ok"}[frozenset({3, 2, 1})]) # hashable: usable as a key
Output · expected
3 True [1, 2, 3] [1, 2, 3, 4] [2, 3] True ok

Unpacking in literals

* spreads an iterable into a list/set literal. ** spreads a mapping into a dict literal. Mix freely with regular elements. For dicts, later keys win.

xs = [1, 2] print([*xs, 3, *xs]) # list spread print({*xs, 2, 3}) # set spread (deduped) a = {"x": 1} print({**a, "y": 2, **{"x": 9}}) # dict spread, later key wins
Output · expected
[1, 2, 3, 1, 2] {1, 2, 3} {'x': 9, 'y': 2}

Range

Lazy integer sequence. range(stop), range(start, stop), range(start, stop, step).

print(list(range(5))) print(list(range(2, 8))) print(list(range(0, 10, 2))) print(list(range(10, 0, -1)))
Output · expected
[0, 1, 2, 3, 4] [2, 3, 4, 5, 6, 7] [0, 2, 4, 6, 8] [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

NoneType

Single value, single type.

print(None) print(None is None) print(type(None))
Output · expected
None True <class 'NoneType'>

Ellipsis

... is a singleton of type ellipsis. It compares equal only to itself. It is distinct from '...'.

print(...) print(... is ...) print(type(...)) print(... == '...')
Output · expected
Ellipsis True <class 'ellipsis'> False

Conversions

print(int("42")) print(int(3.7)) # truncates toward zero print(int(True)) print(float("3.14")) print(str(42)) print(str([1, 2])) print(bool([])) # empty is falsy print(bool([0])) # non-empty is truthy print(list("abc")) print(tuple([1, 2, 3])) print(set([1, 1, 2]))
Output · expected
42 3 1 3.14 42 [1, 2] False True ['a', 'b', 'c'] (1, 2, 3) {2, 1}

Truthy and falsy

Falsy values (everything else is truthy):

Falsy values
None
False
0, 0.0
"" (empty string)
[], ()
{}, set()
range(0)
Last updated on