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,0Integers (unlimited precision)[1]
1.23,3.14e-10,4E210,4.0e+210,1.,.1Floating-point (normally implemented as C doubles in CPython)
0o177,0x9ff,0b1111Octal, hex, and binary literals for integers[2]
3+4j,3.0+4.0j,3JComplex 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access