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, sincekeysis 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, sincekeysresults are view objects, not lists.X=A or B or NoneassignsXto the first true object amongAandB, orNoneif both are false (i.e., 0 or empty).X,Y = Y,Xswaps the values ofXandY.red, green, blue = range(3)assigns integer series.Use
try/finallystatements to ensure that arbitrary termination code is run; especially useful around locking calls (acquire before thetry, release in thefinally).Use
with/asstatements ...
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