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 inD.keys( ):to iterate through dictionaries; uses K=D.keys( );K.sort( )to order.X
=AorBor Noneassigns X to the first true object among A and B, orNoneif 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/envpythonor#!/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”), oroutput=os.popen(“cmd”).read( ), oros.fork/execv.The
dir( [object])function is useful for inspecting attribute namespaces;__doc__often is documentation.printandraw_input( )usesys.stdout/stdinstreams: 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: http://www.python.org (Python home),
http://rmi.net/~lutz(updates to this).You should always say “spam” and “eggs” instead of “foo” and “bar” in Python examples. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access