Python Idioms and Hints
This section lists common Python coding tricks and general usage hints. Consult the Python Library Reference and Python Language Reference (http://www.python.org/doc/) for further information on topics mentioned here.
Core Language Hints
S[:]makes a top-level (shallow) copy of any sequence;
copy.deepcopy(X)makes full copies;
D.copy()copy lists and dictionaries.
L[:0]=[X,Y,Z]inserts items at front of list
[X,Y,Z]all insert multiple items at the end of a list, in-place.
X=L.pop()can be used to implement in-place stack operations, where the end of the list is the top of the stack.
for key in D.keys():to iterate through dictionaries, or simply
for key in D:in version 2.2 and later. In Python 3.0 these two forms are equivalent, since
keysis an iterable view.
for key in sorted(D):to iterate over dictionary keys in sorted fashion in version 2.4 and later; the form
K=D.keys(); K.sort(); for key in K:also works in Python 2.X but not Python 3.0, since
keysresults are view objects, not lists.
X=A or B or Noneassigns
Xto the first true object among
Noneif both are false (i.e., 0 or empty).
X,Y = Y,Xswaps the values of
red, green, blue = range(3)assigns integer series.
try/finallystatements to ensure that arbitrary termination code is run; especially useful around locking calls (acquire before the
try, release in the