There are many tips and tricks you can learn in Python:
(but don't worry about this unless your resulting string is more than 500-1000 characters long)[1]
print"Spam"+" eggs"+" and"+" spam"# DON'T DO THISprint" ".join(["Spam","eggs","and","spam"])# Much faster/more# common Python idiomprint"%s%s%s%s"%("Spam","eggs","and","spam")# Also a pythonic way of# doing it - very fast
Several modules have optimized versions written in C, which provide an almost-identical interface and are frequentlymuch faster or more memory-efficient than the pure Python implementations. Module behavior generally does differ in some respects, often minor, and thus C versions are frequently used.
This is primarily a Python 2.x feature, which has been largely removed in Python 3, with modules automatically using optimized implementations if available.[2] However, thecProfile
/profile
pair still exists (as of Python 3.4).
The C version of a module namedmodule
orModule
is calledcModule
, and frequently imported usingimport...as
to strip off the prefix, as:
importcPickleaspickle
For compatibility, one can try to import the C version and fall back to the Python version if the C version is not available; in this case usingimport...as
isrequired, so the code does not depend on which module was imported:
try:importcPickleaspickleexceptImportError:importpickle
Notable examples include:
cPickle
forpickle
, up to 1000× faster.cStringIO
forStringIO
, replaced byio.StringIO
in Python 3cProfile
forprofile
– the Pythonprofile
adds significant overhead, and thuscProfile
is recommended for most use.cElementTree
forElementTree
, 15–20 times faster and uses 2–5 times less memory;[3] not needed in Python 3.3+, which automatically uses a fast implementation if possible.directory=os.listdir(os.getcwd())# Gets a list of files in the# directory the program runs fromfilesInDir=[itemforitemindirectory]# Normal For Loop rules apply, you# can add "if condition" to make a# more narrow search.
[a-bfor(a,b)inzip((1,2,3),(1,2,3))]# will return [0, 0, 0]
Choosing the correct data type can be critical to the performance of an application. For example, say you have 2 lists:
list1=[{'a':1,'b':2},{'c':3,'d':4},{'e':5,'f':6}]list2=[{'e':5,'f':6},{'g':7,'h':8},{'i':9,'j':10}]
and you want to find the entries common to both lists. You could iterate over one list, checking for common items in the other:
common=[]forentryinlist1:ifentryinlist2:common.append(entry)
For such small lists, this will work fine, but for larger lists, for example if each contains thousands of entries, the following will be more efficient, and produces the same result:
set1=set([tuple(entry.items())forentryinlist1])set2=set([tuple(entry.items())forentryinlist2])common=set1.intersection(set2)common=[dict(entry)forentryincommon]
Sets are optimized for speed in such functions. Dictionaries themselves cannot be used as members of a set as they are mutable, but tuples can. If one needs to do set operations on a list of dictionaries, one can convert the items to tuples and the list to a set, perform the operation, then convert back. This is often much faster than trying to replicate set operations using string functions.
defflatten(seq,list=None):"""flatten(seq, list = None) -> list Return a flat version of the iterator `seq` appended to `list` """iflist==None:list=[]try:# Can `seq` be iterated over?foriteminseq:# If so then iterate over `seq`flatten(item,list)# and make the same check on each item.exceptTypeError:# If seq isn't iterablelist.append(seq)# append it to the new list.returnlist
print'Hit Enter to exit'raw_input()
[on_true]if[expression]else[on_false]x,y=50,25small=xifx<yelsey
b=1==1name="I am%s"%["John","Doe"][b]#returns I am Doe