Built-in Types and Operators

Operators and Precedence

Table 1-1 lists Python’s expression operators. Operators in the lower cells of this table have higher precedence (i.e., bind tighter) when used in mixed-operator expressions without parentheses.

Table 1-1. Python 3.0 expression operators and precedence

Operator

Description

yield X

Generator function send() protocol

lambda args: expr

Anonymous function maker

X if Y else Z

Ternary selection (X is evaluated only if Y is true)

X or Y

Logical OR: Y is evaluated only if X is false

X and Y

Logical AND: Y is evaluated only if X is true

not X

Logical negation

X in Y, X not in Y

Membership: iterables, sets

X is Y, X is not Y

Object identity tests

X < Y, X <= Y, X > Y, X >= Y

Magnitude comparisons, set subset and superset

X == Y, X != YEquality operators

X | Y

Bitwise OR, set union

X ^ Y

Bitwise exclusive OR, set symmetric difference

X & Y

Bitwise AND, set intersection

X << Y, X >> Y

Shift X left, right by Y bits

X + Y, X – Y

Addition/concatenation, subtraction/set difference

X * Y, X % Y,

X / Y, X // Y

Multiplication/repetition, remainder/format, division, floor division

-X, +X

Unary negation, identity

˜X

Bitwise NOT complement (inversion)

X ** Y

Power (exponentiation)

X[i]

Indexing (sequence, mapping, others)

X[i:j:k]

Slicing (all bounds optional)

X(...)

Call (function, method, class, other callable)

X.attr

Attribute reference

(...)

Tuple, expression, generator expression

[...]

List, list comprehension

{...}

Dictionary, set, dictionary and set comprehension

Operator Usage Notes

  • In Python 2.6, value inequality can be written as either X != Y or X <> Y. In Python 3.0, the latter of these options is removed because it is redundant.

  • In Python 2.6, a backquotes expression `X` works the same as repr(X), and converts objects to display strings. In Python 3.0, use the more readable str() and repr() built-in functions instead.

  • In both Python 3.0 and 2.6, the X // Y floor division expression always truncates fractional remainders, and returns an integer result for integers.

  • The X / Y expression performs true division in 3.0 (always retaining remainders in a floating-point result), and classic division in 2.6 (truncating remainders for integers).

  • The syntax [...] is used for both list literals and list comprehension expressions. The latter of these performs an implied loop and collects expression results in a new list.

  • The syntax (...) is used for tuples and expressions, as well as generator expressions—a form of list comprehension that produces results on demand, instead of building a result list. Parenthesis may sometimes be omitted in all three constructs.

  • The syntax {...} is used for dictionary literals. In Python 3.0, it is also used for set literals, and both dictionary and set comprehensions; use set() and looping statements in 2.6.

  • The yield and ternary if/else selection expressions are available in Python 2.5 and later. The former returns send() arguments in generators; the latter is a shorthand for a multiline if statement. yield requires parentheses if not alone on the right side of an assignment statement.

  • Comparison operators may be chained: X < Y < Z produces the same result as X < Y and Y < Z, but Y is evaluated only once in the chained form.

  • The slice expression X[I:J:K] is equivalent to indexing with a slice object: X[slice(I, J, K)].

  • In Python 2.6, magnitude comparisons of mixed types are allowed—converting numbers to a common type, and ordering other mixed types according to the type name. In Python 3.0, nonnumeric mixed-type magnitude comparisons are not allowed, and raise exceptions; this includes sorts by proxy.

  • Magnitude comparisons for dictionaries are also no longer supported in Python 3.0 (though equality tests are); comparing sorted(dict.items()) is one possible replacement in 3.0.

  • Call expressions allow for positional and keyword arguments, and arbitrarily large numbers of both; see The Expression Statement and The def Statement for call syntax.

  • Python 3.0 allows ellipsis (literally, ...) to be used as an atomic expression anywhere in source code. This may be used as an alternative to pass or None in some contexts (e.g., stubbed-out function bodies, type-independent variable initialization).

Operations by Category

All built-in types support the comparisons and Boolean operations listed in Table 1-2.

Boolean true means any nonzero number or any nonempty collection object (list, dictionary, etc.). The built-in names True and False are pre-assigned to true and false values and behave like integers 1 and 0 with custom display formats. The special object None is false.

Comparisons return True or False and are applied recursively in compound objects as needed to determine a result.

Boolean and and or operators stop (short-circuit) as soon as a result is known and return one of the two operand objects (on left or right).

Table 1-2. Comparisons and Boolean operations

Operator

Description

X < Y

Strictly less than[a]

X <= Y

Less than or equal to

X > Y

Strictly greater than

X >= Y

Greater than or equal to

X == Y

Equal to (same value)

X != Y

Not equal to (same as X<>Y in Python 2.6 only)[b]

X is Y

Same object

X is not Y

Negated object identity

X < Y < Z

Chained comparisons

not X

If X is false then True; else, False

X or Y

If X is false then Y; else, X

X and Y

If X is false then X; else, Y

[a] To implement comparison expressions, see both the rich comparison (e.g., __lt__ for <) class methods in 3.0 and 2.6, and general __cmp__ method in 2.6, described in the section Operator Overloading Methods.

[b] != and <> both mean not equal by value in 2.6, but != is the preferred syntax in 2.6, and the only supported option in 3.0. is performs an identity test; == performs value comparison, and so is much more generally useful.

Tables 1-3 through 1-6 define operations common to types in the three major type categories (sequence, mapping, and number), as well as operations available for mutable (changeable) types in Python. Most types also export additional type-specific operations (e.g., methods), as described in the section Specific Built-in Types.

Table 1-3. Sequence operations (strings, lists, tuples, bytes, bytearray)

Operation

Description

Class method

X in S

X not in S

Membership tests

__contains__,

__iter__,

__getitem__[a]

S1 + S2

Concatenation

__add__

S * N, N * S

Repetition

__mul__

S[i]

Index by offset

__getitem__

S[i:j], S[i:j:k]

Slicing: items in S from offset i through j-1 by optional stride k

__getitem__[b]

len(S)

Length

__len__

min(S), max(S)

Minimum, maximum item

__iter__,

__getitem__

iter(S)

Iteration protocol

__iter__

for X in S:,

[expr for X in S],

map(func, S), etc.

Iteration (all contexts)

__iter__,

__getitem__

[a] See also iterators, generators, and the __iter__ class method (see the section The yield Statement). If defined, __contains__ is preferred over __iter__, and __iter__ is preferred over __getitem__.

[b] In Python 2.6, you may also define __getslice__, __setslice__, and __delslice__ to handle slicing operations. In 3.0, these are removed in favor of passing slice objects to their item-based indexing counterparts. Slice objects may be used explicitly in indexing expressions in place of i:j:k bounds.

Table 1-4. Mutable sequence operations (lists, bytearray)

Operation

Description

Class method

S[i] = X

Index assignment: change item at existing offset i

__setitem__

S[i:j] = S2,

S[i:j:k] = S2

Slice assignment: S from i to j is replaced by S2, with optional stride k

__setitem__

del S[i]

Index deletion

__delitem__

del S[i:j],

del S[i:j:k]

Slice deletion

__delitem__

Table 1-5. Mapping operations (dictionaries)

Operation

Description

Class method

D[k]

Index by key

__getitem__

D[k] = X

Key assignment: change or create entry for key k

__setitem__

del D[k]

Delete item by key

__delitem__

len(D)

Length (number of keys)

__len__

k in D

Key membership test[a]

Same as in Table 1-3

k not in D

Converse of k in D

Same as in Table 1-3

iter(S)

Iterator object for keys

Same as in Table 1-3

for k in D:, etc.

Iterate through keys in D (all iteration contexts)

Same as in Table 1-3

[a] In Python 2.X, key membership may also be coded as D.has_key(K). This method is removed in Python 3.0 in favor of the in expression, which is also generally preferred in 2.6. See Dictionaries.

Table 1-6. Numeric operations (all number types)

Operation

Description

Class method

X + Y, X – Y

Add, subtract

__add__, __sub__

X * Y, X / Y,

X // Y, X % Y

Multiply, divide, floor divide, remainder

__mul__, __truediv__,

__floordiv__, __mod__

-X, +X

Negative, identity

__neg__, __pos__

X | Y, X & Y,

X ^ Y

Bitwise OR, AND, exclusive OR (integers)

__or__, __and__, __xor__

X << N, X >> N

Bitwise left-shift, right-shift (integers)

__lshift__, __rshift__

˜X

Bitwise invert (integers)

__invert__

X ** Y

X to the power Y

__pow__

abs(X)

Absolute value

__abs__

int(X)

Convert to integer[a]

__int__

float(X)

Convert to float

__float__

complex(X), complex(re,im)

Make a complex value

__complex__

divmod(X, Y)

Tuple: (X/Y, X%Y)

__divmod__

pow(X, Y [,Z])

Raise to a power

__pow__

[a] In Python 2.6, the long() built-in function invokes the __long__ class method. In Python 3.0, the int type subsumes long, which is removed.

Sequence Operation Notes

Indexing: S[i]

  • Fetches components at offsets (first item is at offset 0).

  • Negative indexes mean to count backward from the end (last item is at offset −1).

  • S[0] fetches the first item.

  • S[−2] fetches the second-to-last item (S[len(S) − 2]).

Slicing: S[i:j]

  • Extracts contiguous sections of a sequence.

  • Slice boundaries default to 0 and sequence length.

  • S[1:3] fetches from offsets 1 up to, but not including, 3.

  • S[1:] fetches from offsets 1 through the end (length-1).

  • S[:−1] fetches from offsets 0 up to, but not including, the last item.

  • S[:] makes a top-level (shallow) copy of sequence object S.

  • Slice assignment is similar to deleting and then inserting.

Slicing: S[i:j:k]

  • If present, the third item k is a stride: added to the offset of each item extracted.

  • S[::2] is every other item in sequence S.

  • S[::−1] is sequence S reversed.

  • S[4:1:−1] fetches from offsets 4 up to, but not including, 1, reversed.

Other

  • Concatenation, repetition, and slicing return new objects (not always for tuples).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset