O'Reilly logo

Python Pocket Reference, 4th Edition by Mark Lutz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required