If you’re an experienced programmer new to Python then I recommend Python Tips by Muhammad Yasoob Ullah Khalid.
List:
[0,1,2]array
Tuple:
(0,1,2)Set:
set([0,1,2]){0,1,2}Dictionary:
{ 'a':1 , 'b':2 }hash() (32-bit)Use range(a) for loops.
Note that range(a,b) returns an empty array if a and b are equal.
slice(start, stop) but use a[start:stop] instead
Numbers:
int(x[, base]): constructor that can also be used to change basechr: character from integer as ASCII codeord: ASCII code to integerdivmod(a,b): return (a // b, a % b) for integersbin, oct and hexabspow: but use x**y insteadString:
ord: return nIterables:
len for lengthnext(iterator[, default]), e.g. next(i, None)all and any: returns true if all/any element are truesortedreversedmin and maxmap(function, iterable) and reduce(function, iterable[, initializer])filter(function, iterable) but use list comprehensions insteadtuple to create a tuple from iterablezip([iterable, ...]): return list of tuples by “zippering” multiple listsenumerate: return list of numbered tuplessomefrom MODULE import NAME1, NAME2, ... to import NAME1 and NAME2 from MODULEfrom MODULE import * to import everything from MODULEfrom .MODULE is relative import (?)Functions can return multiple values:
def return_both(a,b):
return a,b
x,y = return_both(1,2)
You can put multiple statements on one line by using a semi-colon, e.g. i += 1; j += 1 but this is discouraged.
Perhaps only do this on a whiteboard or doc to save space.
Get an object’s reference count: sys.getrefcount(obj)
pip is the python package manager
sudo easy_install pip to install pippip will show you available commands
pip search <keyword>pip install <package>pip freeze prints installed packages in “requirements” format
pip help <command> will show you extended –help for a commandsetuptools is the fundamental pip dependency
virtualenv creates a virtual environment for each program with:
pythonpipInstallation:
pip install virtualenvpip install virtualenvwrappermkvirtualenv <name_of_env> to create a virtual envworkon <name_of_env> to source (use) a virtual envVirtual environments are not saved in you application folder.
They are located in ~/.virtualenvs/name_of_env
When you pip install a package that contains global binary then it is isntall in ~/.virtualenvs/name_of_env/bin
A Byte of Python. Swaroop Chitlur.
A non-magical introduction to Pip and Virtualenv for Python beginners. Jamie Matthews. 2013-04-18.
Design and History FAQ. Python Documentation.
The Mighty Dictionary. Brandon Craig Rhodes. PyCon 2010. An optimized explanation of Python’s Dictionary implementation using a hash table.