The "Unknown:"s below indicate that an entry is incomplete.
- Category: Object Oriented, Dynamically typed, Has anonymous functions
- Various
indentation block (grouping statements, especially when statements are not expressions)
\ breaking lines (useful when end-of-line and/or indentation has a special meaning)
# commenting (until end of line)
< > <= >= comparison
min / max comparison (min / max (binary or more))
cmp comparison (returns 3 values (i.e. inferior, equal or superior))
class X:
"""...
"""
def x():
"""...
"""
(1) documentation comment
== != equality / inequality (deep)
== <> equality / inequality (deep)
is / is not equality / inequality (shallow)
gc.collect() force garbage collection
( ... ) grouping expressions
__file__ information about the current line and file
eval runtime evaluation
exec runtime evaluation
case-sensitive tokens (case-sensitivity (keywords, variable identifiers...))
[_a-zA-Z][_a-zA-Z0-9]* tokens (variable identifier regexp)
= variable assignment or declaration (both)
global v1, v2 variable assignment or declaration (declaration)
- Functions
functools.partial(f, a)(2) partial application (in the examples below, a normal call is "f(a,b)") (give the first argument)
lambda a, b: ... anonymous function
f(a,b,...) function call
f() function call (with no parameter)
__getattr__ function called when a function is not defined (in dynamic languages)
def f(para1, para2, ...): ... function definition
return(3) function return value (breaks the control flow)
inspect.stack()[1] runtime inspecting the caller information
- Control Flow
continue / break breaking control flow (continue / break)
return(3) breaking control flow (returning a value)
try: a except exn: ... exception (catching)
finally exception (cleanup: code executed before leaving)
raise exception (throwing)
if c: ... if_then
b1 if c else b2(2) if_then_else
if c:
b1
elif c2:
b2
else:
b3
if_then_else
for i in xrange(10, 0, -1) loop (for each value in a numeric range, 1 decrement)
for i in xrange(1, 11) loop (for each value in a numeric range, 1 increment (see also the entries about ranges))
for i in xrange(1, 11, 2) loop (for each value in a numeric range, free increment)
while c: ... loop (while condition do something)
; sequence
end-of-line sequence
- Types
t(e) cast (computed conversion (calls an internal or a user-defined function))
n = t declaration
- Object Oriented & Reflexivity
super(Class, self).meth(args) accessing parent method
class class declaration
first parameter(4) current instance
__class__ get the type/class corresponding to an object/instance/value
hasattr(obj, "meth")(5) has the method
class child(parent): inheritance
del, __del__ manually call an object's destructor
object.method(para) method invocation
object.method() method invocation (with no parameter)
dir methods available
copy.copy(o)(6) object cloning
class_name(...) object creation
isinstance testing class membership
- Package, Module
automatically done based on the file name declare
__all__ = [ ... ] declare (selective export)
from p import * import (everything into current namespace)
import p import (package (ie. load the package))
from p import name1, name2, ... import (selectively)
. package scope
- Strings
s[n] accessing n-th character
chr ascii to character
ord character to ascii
str, `e`, repr convert something to a string (see also string interpolation)
* duplicate n times
s[n:m+1] extract a substring
index locate a substring
find locate a substring
rindex locate a substring (starting at the end)
rfind locate a substring (starting at the end)
'''...''', """...""" multi-line
pickle.dump(7) serialize (marshalling)
print(8) simple print (on any objects)
print e, simple print (on any objects)
% sprintf-like
+ string concatenation
== != string equality & inequality
== <> string equality & inequality
len string size
"\n" strings (end-of-line (without writing the real CR or LF character))
"... %(v)s ..." % vars() strings (with interpolation of variables)
'...' strings (with no interpolation of variables)
"..." strings (with no interpolation of variables)
'''...''' strings (with no interpolation of variables)
"""...""" strings (with no interpolation of variables)
str type name
pickle.load unserialize (un-marshalling)
upper / lower(9) upper / lower case character
upper / lower / capitalize uppercase / lowercase / capitalized string
- Booleans
False false value
None false value
"" false value
() false value
[] false value
{} false value
or / and logical or / and (short circuit)
True true value
anything not false true value
bool type name
- Bags and Lists
zip(*l) 2 lists from a list of couples
a.insert(i, e) adding an element at index (side-effect)
append adding an element at the end (side-effect)
l[1:] all but the first element
reduce(12) f(... f(f(init, e1), e2) ..., en)
index find an element
for v in l: ... for each element do something
pop get the last element and remove it
in is an element in the list
any(2) is the predicate true for an element
all(2) is the predicate true for every element
enumerate(l) iterate with index
s.join(l) join a list of strings in a string using a glue string
filter keep elements (matching)
[ x for x in l if p(x) ](13) keep elements (matching)
a[-1] last element
+ list concatenation
[ a, b, c ](14) list constructor
zip list of couples from 2 lists
list list out of a bag
len list size
a[i] list/array indexing
set remove duplicates
reverse reverse
reversed reverse
l[::-1] reverse
min / max smallest / biggest element
sorted sort
map transform a list (or bag) in another one
[ f(x) for x in l ](13) transform a list (or bag) in another one
map transform two lists in parallel
list type name
- Various Data Types
a, computable tuple (these are a kind of immutable lists playing a special role in parameter passing) (1-uple)
tuple([a]) computable tuple (these are a kind of immutable lists playing a special role in parameter passing) (1-uple)
() computable tuple (these are a kind of immutable lists playing a special role in parameter passing) (empty tuple)
*t computable tuple (these are a kind of immutable lists playing a special role in parameter passing) (using a tuple for a function call)
h.get(k, returned_value_when_k_unfound) dictionary (access: read)
h[k] dictionary (access: read/write)
{ a: b, c: d } dictionary (constructor)
has_key dictionary (has the key ?)
k in h dictionary (has the key ?)
k not in h dictionary (has the key ?)
keys dictionary (list of keys)
values dictionary (list of values)
update(16) dictionary (merge)
del h[k] dictionary (remove by key)
dict dictionary (type name)
or optional value (null coalescing)
None optional value (null value)
v optional value (value)
range range (inclusive .. exclusive)
. record (selector)
a, b, c tuple constructor
tuple tuple type
- Mathematics
+ / - / * / / addition / subtraction / multiplication / division
& / | / ^ bitwise operators (and / or / xor)
~ bitwise operators (bitwise inversion)
<< / >> bitwise operators (left shift / right shift / unsigned right shift)
divmod euclidean division (both quotient and modulo)
** exponentiation (power)
pow exponentiation (power)
log10 logarithm (base 10)
log(val, 2) logarithm (base 2)
log logarithm (base e)
% modulo (modulo of -3 / 2 is 1)
- negation
1000., 1E3 numbers syntax (floating point)
07, 0xf numbers syntax (integers in base 2, octal and hexadecimal)
1000 numbers syntax (integers)
mathematical operator priorities and associativities (addition vs multiplication)
mathematical operator priorities and associativities (exponentiation vs negation (is -3^2 equal to 9 or -9))
random random (random number)
random.seed random (seed the pseudo random generator)
sqrt / exp / abs square root / e-exponential / absolute value
sin / cos / tan trigonometry (basic)
asin / acos / atan(17) trigonometry (inverse)
int / round / floor / ceil truncate / round / floor / ceil
float, decimal.Decimal type name (floating point)
int, long(18) type name (integers)
- Threads
OtherThread.join() Joining Another Thread (Suspending a thread until another thread completes)
class class_name(threading.Thread) {[override run method] } thread definition
.