Computer Science 15-112, Fall 2011
Class Notes: Data and Expressions
Excerpts from:
Python Standard Library, Ch 5 (Built-In Types), 5.1 through 5.4
The following sections describe the standard types that are built into the interpreter.
Note: Historically (until release 2.2), Python’s built-in types have differed from user-defined types because it was not possible to use the built-in types as the basis for object-oriented inheritance. This limitation no longer exists.
The principal built-in types are numerics, sequences, mappings, files, classes, instances and exceptions.
Some operations are supported by several object types; in particular, practically all objects can be compared, tested for truth value, and converted to a string (with the repr() function or the slightly different str() function). The latter function is implicitly used when an object is written by the print() function.
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
None
False
zero of any numeric type, for example, 0, 0L, 0.0, 0j.
any empty sequence, for example, '', (), [].
any empty mapping, for example, {}.
instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False. [1]
All other values are considered true — so objects of many types are always true.
Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)
These are the Boolean operations, ordered by ascending priority:
Operation | Result | Notes |
---|---|---|
x or y | if x is false, then y, else x | (1) |
x and y | if x is false, then x, else y | (2) |
not x | if x is false, then True, else False | (3) |
Notes:
Comparison operations are supported by all objects. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).
This table summarizes the comparison operations:
Operation | Meaning | Notes |
---|---|---|
< | strictly less than | |
<= | less than or equal | |
> | strictly greater than | |
>= | greater than or equal | |
== | equal | |
!= | not equal | (1) |
is | object identity | |
is not | negated object identity |
Notes:
Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result). Furthermore, some types (for example, file objects) support only a degenerate notion of comparison where any two objects of that type are unequal. Again, such objects are ordered arbitrarily but consistently. The <, <=, > and >= operators will raise a TypeError exception when any operand is a complex number.
Instances of a class normally compare as non-equal unless the class defines the __cmp__() method. Refer to Basic customization) for information on the use of this method to effect object comparisons.
Two more operations with the same syntactic priority, in and not in, are supported only by sequence types (below).
There are four distinct numeric types: plain integers, long integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of plain integers. Plain integers (also just called integers) are implemented using long in C, which gives them at least 32 bits of precision (sys.maxint is always set to the maximum plain integer value for the current platform, the minimum value is -sys.maxint - 1). Long integers have unlimited precision. Floating point numbers are usually implemented using double in C; information about the precision and internal representation of floating point numbers for the machine on which your program is running is available in sys.float_info. Complex numbers have a real and imaginary part, which are each a floating point number. To extract these parts from a complex number z, use z.real and z.imag. (The standard library includes additional numeric types, fractions that hold rationals, and decimal that hold floating-point numbers with user-definable precision.)
Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals (including binary, hex, and octal numbers) yield plain integers unless the value they denote is too large to be represented as a plain integer, in which case they yield a long integer. Integer literals with an 'L' or 'l' suffix yield long integers ('L' is preferred because 1l looks too much like eleven!). Numeric literals containing a decimal point or an exponent sign yield floating point numbers. Appending 'j' or 'J' to a numeric literal yields a complex number with a zero real part. A complex numeric literal is the sum of a real and an imaginary part.
Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the “narrower” type is widened to that of the other, where plain integer is narrower than long integer is narrower than floating point is narrower than complex. Comparisons between numbers of mixed type use the same rule. [2] The constructors int(), long(), float(), and complex() can be used to produce numbers of a specific type.
All built-in numeric types support the following operations. See The power operator and later sections for the operators’ priorities.
Operation | Result | Notes |
---|---|---|
x + y | sum of x and y | |
x - y | difference of x and y | |
x * y | product of x and y | |
x / y | quotient of x and y | (1) |
x // y | (floored) quotient of x and y | (4)(5) |
x % y | remainder of x / y | (4) |
-x | x negated | |
+x | x unchanged | |
abs(x) | absolute value or magnitude of x | (3) |
int(x) | x converted to integer | (2) |
long(x) | x converted to long integer | (2) |
float(x) | x converted to floating point | (6) |
complex(re,im) | a complex number with real part re, imaginary part im. im defaults to zero. | |
c.conjugate() | conjugate of the complex number c. (Identity on real numbers) | |
divmod(x, y) | the pair (x // y, x % y) | (3)(4) |
pow(x, y) | x to the power y | (3)(7) |
x ** y | x to the power y | (7) |
Notes:
For (plain or long) integer division, the result is an integer. The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result is a long integer if either operand is a long integer, regardless of the numeric value.
Conversion from floats using int() or long() truncates toward zero like the related function, math.trunc(). Use the function math.floor() to round downward and math.ceil() to round upward.
See Built-in Functions for a full description.
Deprecated since version 2.3: The floor division operator, the modulo operator, and the divmod() function are no longer defined for complex numbers. Instead, convert to a floating point number using the abs() function if appropriate.
Also referred to as integer division. The resultant value is a whole integer, though the result’s type is not necessarily int.
float also accepts the strings “nan” and “inf” with an optional prefix “+” or “-” for Not a Number (NaN) and positive or negative infinity.
New in version 2.6.
Python defines pow(0, 0) and 0 ** 0 to be 1, as is common for programming languages.
All numbers.Real types (int, long, and float) also include the following operations:
Operation | Result | Notes |
---|---|---|
math.trunc(x) | x truncated to Integral | |
round(x[, n]) | x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0. | |
math.floor(x) | the greatest integral float <= x | |
math.ceil(x) | the least integral float >= x |
Plain and long integer types support additional operations that make sense only for bit-strings. Negative numbers are treated as their 2’s complement value (for long integers, this assumes a sufficiently large number of bits that no overflow occurs during the operation).
The priorities of the binary bitwise operations are all lower than the numeric operations and higher than the comparisons; the unary operation ~ has the same priority as the other unary numeric operations (+ and -).
This table lists the bit-string operations sorted in ascending priority:
Operation | Result | Notes |
---|---|---|
x | y | bitwise or of x and y | |
x ^ y | bitwise exclusive or of x and y | |
x & y | bitwise and of x and y | |
x << n | x shifted left by n bits | (1)(2) |
x >> n | x shifted right by n bits | (1)(3) |
~x | the bits of x inverted |
Notes:
The integer types implement the numbers.Integral abstract base class. In addition, they provide one more method:
>>> n = -37
>>> bin(n)
'-0b100101'
>>> n.bit_length()
6
More precisely, if x is nonzero, then x.bit_length() is the unique positive integer k such that 2**(k-1) <= abs(x) < 2**k. Equivalently, when abs(x) is small enough to have a correctly rounded logarithm, then k = 1 + int(log(abs(x), 2)). If x is zero, then x.bit_length() returns 0.
Equivalent to:
def bit_length(self):
s = bin(self) # binary representation: bin(-37) --> '-0b100101'
s = s.lstrip('-0b') # remove leading zeros and minus sign
return len(s) # len('100101') --> 6
New in version 2.7.
The float type implements the numbers.Real abstract base class. float also has the following additional methods.
New in version 2.6.
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
New in version 2.6.
Two methods support conversion to and from hexadecimal strings. Since Python’s floats are stored internally as binary numbers, converting a float to or from a decimal string usually involves a small rounding error. In contrast, hexadecimal strings allow exact representation and specification of floating-point numbers. This can be useful when debugging, and in numerical work.
New in version 2.6.
New in version 2.6.
Note that float.hex() is an instance method, while float.fromhex() is a class method.
A hexadecimal string takes the form:
[sign] ['0x'] integer ['.' fraction] ['p' exponent]
where the optional sign may by either + or -, integer and fraction are strings of hexadecimal digits, and exponent is a decimal integer with an optional leading sign. Case is not significant, and there must be at least one hexadecimal digit in either the integer or the fraction. This syntax is similar to the syntax specified in section 6.4.4.2 of the C99 standard, and also to the syntax used in Java 1.5 onwards. In particular, the output of float.hex() is usable as a hexadecimal floating-point literal in C or Java code, and hexadecimal strings produced by C’s %a format character or Java’s Double.toHexString are accepted by float.fromhex().
Note that the exponent is written in decimal rather than hexadecimal, and that it gives the power of 2 by which to multiply the coefficient. For example, the hexadecimal string 0x3.a7p10 represents the floating-point number (3 + 10./16 + 7./16**2) * 2.0**10, or 3740.0:
>>> float.fromhex('0x3.a7p10')
3740.0
Applying the reverse conversion to 3740.0 gives a different hexadecimal string representing the same number:
>>> float.hex(3740.0)
'0x1.d380000000000p+11'
carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem