Python Idioms and 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 ] inserts at end (in-place “+”).

  • Uses for key in D.keys( ): to iterate through dictionaries; uses K=D.keys( ); K.sort( ) to order.

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

  • X, Y = Y, X swaps the values of X and Y; red, green, blue = range(3) assigns integer series.

  • Uses if __name__ == ‘__main__’: to add self-test code at the bottom of module files (true when run only).

  • To make a file an executable script, add line at top like #!/usr/bin/env python or #!/usr/local/bin/python.

  • Command-line arguments: sys.argv, environment: os.environ, streams: sys.stdin/stdout/stderror, filename expansion: glob.glob(“pattern”).

  • To run shell commands: os.system(cmd”), or output=os.popen(“cmd”).read( ), or os.fork/execv.

  • The dir( [object ]) function is useful for inspecting attribute namespaces; __doc__ often is documentation.

  • print and raw_input( ) use sys.stdout/stdin streams: assign to file-like objects to redirect I/O internally.

  • See Python references and books for topics skipped here: Python/C integration API, Tkinter GUI API, Windows tools (COM/ActiveX), Internet modules, JPython, etc.

  • Important web sites: (Python home), (updates to this).

  • You should always say “spam” and “eggs” instead of “foo” and “bar” in Python examples. ...

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

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