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
=
Aor
Bor None
assigns X to the first true object among A and B, orNone
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”)
, oroutput=os.popen(“
cmd”).read( )
, oros.fork/execv
.The
dir( [
object])
function is useful for inspecting attribute namespaces;__doc__
often is documentation.print
andraw_input( )
usesys.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: http://www.python.org (Python home),
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 books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.