Python Idioms and Hints

This section lists common Python coding tricks and general usage hints. Consult the Python Library Reference and Python Language Reference ( for further information on topics mentioned here.

Core Language Hints

  • S[:] makes a top-level copy of any sequence object; copy.deepcopy(X) makes full copies.

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

  • L[len(L):]=[X,Y,Z] and L.extend([X,Y,Z]) insert items at end (like in-place “+”).

  • L.append(X) and X=L.pop( ) can be used to implement in-place stack operations.

  • Use for key in D.keys( ): to iterate through dictionaries, or simply for key in D: in 2.2.

  • Use K=D.keys( ); K.sort( ); for key in K: for ordered dictionary iteration.

  • 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 termination code is run.

Environment Hints

  • Use if _ _name_ _ == '_ _main_ _': to add self-test code at the bottom of module files; true only when file is run, not when it is imported as a library.

  • To load file contents in a single expression, use bytes=open('filename').read( ).

  • To iterate through text files, use for line in file.xreadlines( ): or simply for line in file: in 2.2.

  • To make a file an executable script on Unix-like platforms, add a line like #!/usr/bin/env python or #!/usr/local/bin/python at the top and give the file ...

Get Python Pocket Reference, Second Edition now with the O’Reilly learning platform.

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