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)
andD.copy()
copy lists and dictionaries.L[:0]=[X,Y,Z]
inserts items at front of listL
, in-place.L[len(L):]=[X,Y,Z]
,L.extend([X,Y,Z])
, andL
+=
[X,Y,Z]
all insert multiple items at the end of a list, in-place.L.append(X)
andX=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 simplyfor key in D:
in version 2.2 and later. In Python 3.0 these two forms are equivalent, sincekeys
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 formK=D.keys(); K.sort(); for key in K:
also works in Python 2.X but not Python 3.0, sincekeys
results are view objects, not lists.X=A or B or None
assignsX
to the first true object amongA
andB
, orNone
if both are false (i.e., 0 or empty).X,Y = Y,X
swaps the values ofX
andY
.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 thetry
, release in thefinally
).Use
with/as
statements ...
Get Python Pocket Reference, 4th 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.