Specific Built-in Types

This section covers numbers, strings, lists, dictionaries, tuples, files, and other core built-in types. Compound datatypes (e.g., lists, dictionaries, and tuples) can nest inside each other arbitrarily and as deeply as required. Sets may participate in nesting as well, but may contain only immutable objects.

Numbers

This section covers basic number types (integers, floating-point), as well as more advanced types (complex, decimals, and fractions). Numbers are always immutable (unchangeable).

Literals and creation

Numbers are written in a variety of numeric constant forms.

1234, −24, 0

Integers (unlimited precision)[1]

1.23, 3.14e-10, 4E210, 4.0e+210, 1., .1

Floating-point (normally implemented as C doubles in CPython)

0o177, 0x9ff, 0b1111

Octal, hex, and binary literals for integers[2]

3+4j, 3.0+4.0j, 3J

Complex numbers

decimal.Decimal('1.33'), fractions.Fraction(4, 3)

Module-based types: decimal, fraction

int(), float(), complex()

Create numbers from other objects, or from strings with possible base conversion; see Built-in Functions

Operations

Number types support all number operations (see Table 1-6). In mixed-type expressions, Python converts operands up to the type of the “highest” type, where integer is lower than floating-point, which is lower than complex. As of Python 3.0 and 2.6, integer and floating-point objects also have a handful of methods and other attributes; see Python’s Library Reference manual for details.

>>> (2.5).as_integer_ratio() # float attributes ...

Get Python Pocket Reference, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.