-
abs(x) - return absolute value of x.
abs(-5.5) # 5.5
abs(3) # 3
-
bool(x) - convert to boolean value.
bool(1) # True
bool(-1) # True
bool(0) # False
bool([]) # False
-
callable(x) - return True if x may be callable, False if it is not. NOTE: if True is returned, it is not always guaranteed that argument is callable, there may be some cases when it is not, but if False is returned, the argument is definitely not callable.
def f(): pass
callable(f) # True
callable(5) # False
-
chr(i) - return string of one char whose ASCII code is integer i.
chr(97) # 'a'
chr(80) # 'P'
-
cmp(x,y) - compare x to y.
cmp(2,1) # 1
cmp(1,2) # -1
cmp(2,2) # 0
cmp('a','n') # -1
-
compile(string, filename, kind [, flags[, dont_inherit]]) - compile string into code object.
cobj = compile("print 'Hello!'", "<string>", "exec")
exec(cobj) # Hello!
cobj = compile("print 'Hello!\n 2nd line\n'", "<string>", "exec")
exec(cobj) # Hello!
2nd line
cobj = compile("5+6", "<string>", "eval")
print exec(cobj) # 11
# Note that multiple lines have to be separated by '\n' and input must be
# terminated by '\n'
-
complex([real[, imag]]) - Create complex number.
complex(5,8) # (5+8j)
-
delattr(object, name) - Delete an attribute of an object.
class X: pass
x = X()
x.y = 5
delattr(x, "y")
print x.y # AttributeError
-
dict([mapping-or-sequence]) - Return new dict initialized from argument or a set of keyword arguments.
dict([["two", 3], ["one", 2]]) # {"two":3, "one":2}
dict(one=2, two=3) # {"two":3, "one":2}
-
dir(object) - Return the list of names in current local symbol table without arguments; with arguments - attempt to return a list of valid attributes for that object.
dir('a') # [list of attributes for strings].
import struct
dir() # ['__builtins__', '__doc__', '__name__', 'struct']
dir(struct) # ['__doc__', '__name__', 'calcsize', 'error', 'pack', 'unpack']
-
divmod(a, b) - Return quotient and remainder when using long division.
divmod(10,3) # (3, 1)
divmod(15,5) # (3, 0)
-
enumerate(iterable) - Return an enumerate object.
x = enumerate((5,3,18))
for i, num in x: print i, num
0 5
1 3
2 18
-
eval(expression[, globals[, locals]]) - Evaluate expression.
x = 5
eval("x+1") # 6
eval("print 5") # [SyntaxError, because this is a statement, not an expression]
-
execfile(filename[, globals[, locals]]) - Execute contents of the file.
contents of file "myfile.txt": print 'Hello!'
execfile("myfile.txt") # Hello!
-
file(filename[, mode[, bufsize]]) - Return a new file object (same as open()).
x = file("myfile.txt") # open file for reading
x = file("myfile.txt", "w") # open file for writing
x = file("myfile.txt", "a") # open file for appending
x = file("myfile.txt", "r+") # open file for updating
x = file("myfile.txt", "w+") # open file for updating (truncate file)
x = file("myfile.txt", "rb") # open file for reading in binary mode
-
filter(function, list) - Filter list through a function.
def is_five(x):
if x==5: return True
y = [1,5,8,9,5,11]
filter(is_five, y) # [5,5]
-
float([x]) - Convert x to float.
float(5) # 5.0
float("5") # 5.0
-
frozenset(iterable) - Return a frozenset object (sets that have no update methods).
x = frozenset([5,3,8])
x[1] = 9 # [TypeError]
-
getattr(object, name[, default]) - Return an attribute of an object.
import string
getattr(string, "digits") # "0123456789"
getattr(string, "dahh", "not-there!") # "not-there!" [because string
# has no attribute 'dahh']
-
globals() - Return dictionary of current globals namespace.
globals() # {'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__',
'__doc__': None, 'cobj': <code object <module> at 00AE4D58, file "", line 1>}
-
hasattr(object, name) - Returns True if object has attribute and False otherwise.
import string
hasattr(string, "digits") # True
hasattr(string, "duh") # False
-
hash(object) - Return hash value of object if it has one.
hash(5) # 5
hash("abc") # -1600925533
hash((1,2,3)) # -378539185
hash([1,2,3]) # [TypeError: list object are not hashable.]
hash({}) # [TypeError: dict object are not hashable.]
-
help(object) - Return help string for the object.
import string
help(string) # Name: string - A collection of string operations [...]
help(string.atoi) # Help on function atoi in module string: [...]
-
hex(x) - Return hex value of x.
hex(5) # 0x5
hex(25) # 0x19
hex(-20) # -0x14
-
id(object) - Return "identity" of an object, guaranteed to be unique to the object during its lifetime (implementation detail: this is the address of the object).
id(a) # 10770624
id(520) # 13793008
id(520) # 22140552
a = 520
id(a) # 22260324
id(a) # 22260324
id('abc') # 1149848
-
input(prompt) - equivalent to eval(raw_input(prompt)).
a = 5
input("type an expression: ")
type an expression: [user types in "a + 18" w/o quotes] # 23
-
int([x[, radix]]) - Convert string or number to plain integer, radix arg converts to given base, from 2 to 36.
int(5.5) # 5
int(5.8) # 5
int('5') # 5
int('1010',2) # 10
int('1010',3) # 30
int('AB3',16) # 2739
-
isinstance(object, classinfo) - Return True if object is instance of classinfo or instance of a subclass of classinfo.
isinstance(5, object) # True [object is the most basic class]
-
issubclass(object, classinfo) - Return True if object is instance of a subclass of classinfo.
class X: pass
class Y(X): pass
issubclass(Y, X) # True
-
iter(0[, sentinel]) - Return an iterator object.
class X: def __getitem__(self, n): return (n+2)*3 x = X() i = iter(x) y = 0 for n in i: print "y is", y, ",", if n > 20: break else: print "n is", n y += 1
-
len(s) - Return length of s.
len("abc") # 3
len([1,2,3]) # 3
len({1:2,3:4}) # 2
-
list([sequence]) - Return a list made out of sequence.
list("abc") # ["a", "b", "c"]
list([1,2,3]) # [1,2,3] [copy by value of original list]
list((1,2,3)) # [1,2,3]
-
locals() - Return dict of locals namespace.
locals()
# {'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None}
-
long([x[, radix]]) - Convert string or number to plain long integer, radix arg converts to given base, from 2 to 36.
long(5.5) # 5L
long(5.8) # 5L
long('5') # 5L
long('AB3',16) # 2739L
-
map(function, list, ...) - Apply function to every item of list and return a list of the results.
x = ['a', 'b', 'c']
import string
map(string.upper, x) # ['A', 'B', 'C']
-
max(s[, args]) - With a single argument s, return the largest item of a non-empty sequence (such as a string, tuple or list). With more than one argument, return the largest of the arguments.
max([1,2,3]) # 3
max(1,2,3) # 3
-
min(s[, args]) - With a single argument s, return the smallest item of a non-empty sequence (such as a string, tuple or list). With more than one argument, return the smallest of the arguments.
min([1,2,3]) # 1
min(1,2,3) # 1
-
object() - Return a new featureless object. object() is a base for all new style classes.
o = object()
dir(o)
# ['__class__', '__delattr__', '__doc__', '__getattribute__',
# '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
# '__setattr__', '__str__']
-
oct(x) - Convert an integer number (of any size) to an octal string.
oct(5) # 05
oct(18) # 022
-
ord(c) - Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string.
ord("a") # 97
ord(u"\u2020") # 8224
-
pow(x, y[, z]) - Return x to the power y; if z is present, return x to the power y, modulo z (computed more efficiently than pow(x, y) % z).
pow(5, 3) # 125
pow(5, 3, 2) # 1
-
property( [fget[, fset[, fdel[, doc]]]]) - Return a property attribute for new-style classes (classes that derive from object).
class C(object): def __init__(self): self.__x = None def getx(self): return self.__x def setx(self, value): self.__x = value def delx(self): del self.__x x = property(getx, setx, delx, "I'm the 'x' property.")
-
range([start,] stop[, step]) - This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops.
xrange() is similar but returns an xrange object, which yields the same values without storing them all simultaneously.
range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(1, 11) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
range(0, 30, 5) # [0, 5, 10, 15, 20, 25]
range(0, 10, 3) # [0, 3, 6, 9]
range(0, -10, -1) # [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
range(0) # []
range(1, 0) # []
-
raw_input( [prompt]) - If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:
s = raw_input(': ') # : Monty Python's Flying Circus
print s # "Monty Python's Flying Circus"
-
reduce( function, sequence[, initializer]) - Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value.
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) # 15
# performs addition: ((((1+2)+3)+4)+5)
-
reload(module) - Reload a previously imported module.
reload(mymodule) # changes in mymodule will be loaded.
-
repr(object) - Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function.
repr('a') # "'a'"
repr(5) # '5'
repr([1,2,3]) # '[1,2,3]'
-
reversed(seq) - Return a reversed iterator.
r = reversed((1,2,3))
for i in r: print i, # 3 2 1
-
round(x[, n]) - Return the floating point value x rounded to n digits after the decimal point. If n is omitted, it defaults to zero.
round(5.2544,2) # 5.25
-
set([iterable]) - Return a set whose elements are taken from iterable. The elements must be immutable.
x = set((1,2,3))
print x # set([1,2,3])
-
setattr(object, name, value) - This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value.
class X: pass
x = X()
setattr(x, "y", 5)
x.y # 5
-
slice([start,] stop[, step]) - Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None.
x = range(10) # [0,1,2,3,4,5,6,7,8,9]
s = slice(5)
x[s] # [0,1,2,3,4]
-
sorted(iterable[, cmp[, key[, reverse]]]) - Return a new sorted list from the items in iterable.
x = [3,5,18,1]
y = sorted(x)
y # [1,3,5,18]
-
staticmethod(function) - Return a static method for function.
-
str([object]) - Return a string containing a nicely printable representation of an object. For strings, this returns the string itself.
str("abc") # 'abc'
str("5") # '5'
str([1,2,3]) # '[1,2,3]'
-
sum(sequence[, start]) - Sums start and the items of a sequence, from left to right, and returns the total. start defaults to 0. The sequence's items are normally numbers, and are not allowed to be strings.
sum([5,8]) # 13
sum([5,8], 5) # 18
-
super(type[, object-or-type]) - Return the superclass of type. If the second argument is omitted the super object returned is unbound. If the second argument is an object, isinstance(obj, type) must be true. If the second argument is a type, issubclass(type2, type) must be true. super() only works for new-style classes.
class C(B): def meth(self, arg): super(C, self).meth(arg)
-
tuple(sequence) - Return a tuple whose items are the same and in the same order as sequence's items.
tuple("abc") # ("a", "b", "c")
tuple([1,2,3]) # (1,2,3)
-
type(object) - Return the type of an object.
type("abc") # <type 'str'>
type(1) # <type 'int'>
type(True) # <type 'bool'>
-
unichr(i) - Return the Unicode string of one character whose Unicode code is the integer i.
unichr(97) # u'a'
-
unicode( [object[, encoding [, errors]]]) - Return the Unicode string version
of object using one of the following modes:
If encoding and/or errors are given, unicode() will decode the object which can
either be an 8-bit string or a character buffer using the codec for encoding.
The encoding parameter is a string giving the name of an encoding; if the
encoding is not known, LookupError is raised. Error handling is done according
to errors; this specifies the treatment of characters which are invalid in the
input encoding. If errors is 'strict' (the default), a ValueError is raised on
errors, while a value of 'ignore' causes errors to be silently ignored, and a
value of 'replace' causes the official Unicode replacement character, U+FFFD,
to be used to replace input characters which cannot be decoded.
unicode("abc") # u'abc'
unicode(3) # u'3'
-
vars(object) - Without arguments, return a dictionary corresponding to the current local symbol table. With a module, class or class instance object as argument (or anything else that has a __dict__ attribute), returns a dictionary corresponding to the object's symbol table. The returned dictionary should not be modified: the effects on the corresponding symbol table are undefined.
class X: pass
x = X()
x.y = 5
vars(x) # {'y': 5}
-
zip(iterable) - This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.
zip([1,2,3,4],"abcd") # [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
zip([1],[1,2]) # [(1, 1)]
zip([1,2],[1]) # [(1, 1)]
zip([1,2]) # [(1,), (2,)]
index
