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; list(L) and D.copy() copy lists and dictionaries.

  • L[:0]=[X,Y,Z] inserts items at front of list L, in-place.

  • L[len(L):]=[X,Y,Z], L.extend([X,Y,Z]), and L += [X,Y,Z] all insert multiple items at the end of a list, in-place.

  • L.append(X) and X=L.pop() can be used to implement in-place stack operations, where the end of the list is the top of the stack.

  • Use 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 keys is an iterable view.

  • Use 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 keys results are view objects, not lists.

  • X=A or B or None assigns X to the first true object among A and B, or None if both are false (i.e., 0 or empty).

  • X,Y = Y,X swaps the values of X and Y.

  • red, green, blue = range(3) assigns integer series.

  • Use try/finally statements to ensure that arbitrary termination code is run; especially useful around locking calls (acquire before the try, release in the finally).

  • Use with/as statements ...

Get Python Pocket Reference, 4th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.