This is not a full Python reference by far—you can find that in the standard Python documentation (http://python.org/doc/ref
). Rather, this is a handy “cheat sheet” that can be useful for refreshing your memory as you start out programming in Python. See Appendix D for changes in the language that are introduced in version 3.0.
This section summarizes Python expressions. Table B-1 lists the most important basic (literal) values in Python; Table B-2 lists the Python operators, along with their precedence (those with high precedence are evaluated before those with low precedence); Table B-3 describes some of the most important built-in functions; Tables B-4 through B-6 describe the list methods, dictionary methods, and string methods, respectively.
Type | Description | Syntax Samples |
Integer | Numbers without a fractional part | 42 |
Long integer | Large integer numbers | 42L |
Float | Numbers with a fractional part | 42.5 , 42.5e-2 |
Complex | Sum of a real (integer or float) and imaginary number | 38 + 4j , 42j |
String | An immutable sequence of characters | 'foo' , "bar" , """baz""" , r'
' |
Unicode | An immutable sequence of Unicode characters | u'foo' , u"bar" , u"""baz""" |
Function | Description |
abs(number) |
Returns the absolute value of a number. |
apply(function[, args[, kwds]]) |
Calls a given function, optionally with parameters. |
all(iterable) |
Returns True if all the elements of iterable are true; otherwise, it returns False . |
any(iterable) |
Returns True if any of the elements of iterable are true; otherwise, it returns False . |
basestring() |
An abstract superclass for str and unicode , usable for type checking. |
bool(object) |
Returns True or False , depending on the Boolean value of object . |
callable(object) |
Checks whether an object is callable. |
chr(number) |
Returns a character whose ASCII code is the given number. |
classmethod(func) |
Creates a class method from an instance method (see Chapter 7). |
cmp(x, y) |
Compares x and y . If x < y , it returns a negative number; if x > y , it returns a positive number; and if x == y , it returns zero. |
complex(real[, imag]) |
Returns a complex number with the given real (and, optionally, imaginary) component. |
delattr(object, name) |
Deletes the given attribute from the given object. |
dict([mapping-or-sequence]) |
Constructs a dictionary, optionally from another mapping or a list of (key, value) pairs. May also be called with keyword arguments. |
dir([object]) |
Lists (most of) the names in the currently visible scopes, or optionally (most of) the attributes of the given object. |
divmod(a, b) |
Returns (a//b, a%b) (with some special rules for floats). |
enumerate(iterable) |
Iterates over (index, item) pairs, for all items in iterable . |
eval(string[, globals[, locals]]) |
Evaluates a string containing an expression, optionally in a given global and local scope. |
execfile(file[, globals[, locals]]) |
Executes a Python file, optionally in a given global and local scope. |
file(filename[, mode[, bufsize]]) |
Creates a file object with a given file name, optionally with a given mode and buffer size. |
filter(function, sequence) |
Returns a list of the elements from the given sequence for which function returns true. |
float(object) |
Converts a string or number to a float. |
frozenset([iterable]) |
Creates a set that is immutable, which means it can be added to other sets. |
getattr(object, name[, default]) |
Returns the value of the named attribute of the given object, optionally with a given default value. |
globals() |
Returns a dictionary representing the current global scope. |
hasattr(object, name) |
Checks whether the given object has the named attribute. |
help([object]) |
Invokes the built-in help system, or prints a help message about the given object. |
hex(number) |
Converts a number to a hexadecimal string. |
id(object) |
Returns the unique ID for the given object. |
input([prompt]) |
Equivalent to eval(raw_input(prompt)) . |
int(object[, radix]) |
Converts a string or number (optionally with a given radix) or number to an integer. |
isinstance(object, classinfo) |
Checks whether the given object is an instance of the given classinfo value, which may be a class object, a type object, or a tuple of class and type objects. |
issubclass(class1, class2) |
Checks whether class1 is a subclass of class2 (every class is a subclass of itself). |
iter(object[, sentinel]) |
Returns an iterator object, which is object.__iter__() , an iterator constructed for iterating a sequence (if object supports __getitem__ ), or, if sentinel is supplied, an iterator that keeps calling object in each iteration until sentinel is returned. |
len(object) |
Returns the length (number of items) of the given object. |
list([sequence]) |
Constructs a list, optionally with the same items as the supplied sequence. |
locals() |
Returns a dictionary representing the current local scope (do not modify this dictionary). |
long(object[, radix]) |
Converts a string (optionally with a given radix) or number to a long integer. |
map(function, sequence, ...) |
Creates a list consisting of the values returned by the given function when applying it to the items of the supplied sequence(s). |
max(object1, [object2, ...]) |
If object1 is a nonempty sequence, the largest element is returned; otherwise, the largest of the supplied arguments (object1 , object2 , . . .) is returned. |
min(object1, [object2, ...]) |
If object1 is a nonempty sequence, the smallest element is returned; otherwise, the smallest of the supplied arguments (object1 , object2 , . . .) is returned. |
object() |
Returns an instance of object , the base class for all new style classes. |
oct(number) |
Converts an integer number to an octal string. |
open(filename[, mode[, bufsize]]) |
An alias for file (use open , not file , when opening files). |
ord(char) |
Returns the ASCII value of a single character (a string or Unicode string of length 1). |
pow(x, y[, z]) |
Returns x to the power of y , optionally modulo z . |
property([fget[, fset[, fdel[, doc]]]]) |
Creates a property from a set of accessors (see Chapter 9). |
range([start, ]stop[, step]) |
Returns a numeric range (as a list) with the given start (inclusive, default 0), stop (exclusive), and step (default 1). |
raw_input([prompt]) |
Returns data input by the user as a string, optionally using a given prompt. |
reduce(function, sequence[, initializer]) |
Applies the given function cumulatively to the items of the sequence, using the cumulative result as the first argument and the items as the second argument, optionally with a start value (initializer ). |
reload(module) |
Reloads an already loaded module and returns it. |
repr(object) |
Returns a string representation of the object, often usable as an argument to eval . |
reversed(sequence) |
Returns a reverse iterator over the sequence. |
round(float[, n]) |
Rounds off the given float to n digits after the decimal point (default zero). |
set([iterable]) |
Returns a set whose elements are taken from iterable (if given). |
setattr(object, name, value) |
Sets the named attribute of the given object to the given value. |
sorted(iterable[, cmp][, key][, reverse]) |
Returns a new sorted list from the items in iterable . Optional parameters are the same as for the list method sort . |
staticmethod(func) |
Creates a static (class) method from an instance method (see Chapter 7). |
str(object) |
Returns a nicely formatted string representation of the given object. |
sum(seq[, start]) |
Returns the sum of a sequence of numbers, added to the optional parameter start (default 0). |
super(type[, obj/type]) |
Returns the superclass of the given type (optionally instantiated). |
tuple([sequence]) |
Constructs a tuple, optionally with the same items as the supplied sequence. |
type(object) |
Returns the type of the given object. |
type(name, bases, dict) |
Returns a new type object with the given name, bases, and scope. |
unichr(number) |
The Unicode version of chr . |
unicode(object[, encoding[, errors]]) |
Returns a Unicode encoding of the given object, possibly with a given encoding, and a given mode for handling errors ('strict' , 'replace' , or 'ignore' ; 'strict' is the default). |
vars([object]) |
Returns a dictionary representing the local scope, or a dictionary corresponding to the attributes of the given object (do not modify the returned dictionary, as the result of such a modification is not defined by the language reference). |
xrange([start, ]stop[, step]) |
Similar to range , but the returned object uses less memory, and should be used only for iteration. |
zip(sequence1, ...) |
Returns a list of tuples, where each tuple contains an item from each of the supplied sequences. The returned list has the same length as the shortest of the supplied sequences. |
Method | Description |
aList.append(obj) |
Equivalent to aList[len(aList):len(aList)] = [obj] . |
aList.count(obj) |
Returns the number of indices i for which alist[i] == obj . |
aList.extend(sequence) |
Equivalent to aList[len(aList):len(aList)] = sequence . |
aList.index(obj) |
Returns the smallest i for which aList[i] == obj (or raises a ValueError if no such i exists). |
aList.insert(index, obj) |
Equivalent to aList[index:index] = [obj] if index >= 0 ; if index < 0 , object is prepended to the list. |
aList.pop([index]) |
Removes and returns the item with the given index (default –1). |
aList.remove(obj) |
Equivalent to del aList[aList.index(obj)] . |
aList.reverse() |
Reverses the items of aList in place. |
aList.sort([cmp][, key][, reverse]) |
Sorts the items of aList in place (stable sorting). Can be customized by supplying a comparison function, cmp ; a key function, key , which will create the keys for the sorting); and a reverse flag (a Boolean value). |
This section gives you a quick summary of each of the statement types in Python.
Simple statements consist of a single (logical) line.
Expressions can be statements on their own. This is especially useful if the expression is a function call or a documentation string.
Example:
"This module contains SPAM-related functions."
Assert statements check whether a condition is true and raise an AssertionError
(optionally with a supplied error message) if it isn’t.
Example:
assert age >= 12, 'Children under the age of 12 are not allowed'
Assignment statements bind variables to values. Multiple variables may be assigned to simultaneously (through sequence unpacking) and assignments may be chained.
Examples:
x = 42 # Simple assignment
name, age = 'Gumby', 60 # Sequence unpacking
x = y = z = 10 # Chained assignments
Assignments may be augmented by operators. The operator will then be applied to the existing value of the variable and the new value, and the variable will be rebound to the result. If the original value is mutable, it may be modified instead (with the variable staying bound to the original).
Examples:
x *= 2 # Doubles x
x += 5 # Adds 5 to x
The pass
statement is a “no-op,” which does nothing. It is useful as a placeholder, or as the only statement in syntactically required blocks where you want no action to be performed.
Example:
try: x.name
except AttributeError: pass
else: print 'Hello', x.name
The del
statement unbinds variables and attributes, and removes parts (positions, slices, or slots) from data structures (mappings or sequences). It cannot be used to delete values directly, because values are only deleted through garbage collection.
Examples:
del x # Unbinds a variable
del seq[42] # Deletes a sequence element
del seq[42:] # Deletes a sequence slice
del map['foo'] # Deletes a mapping item
The print
statement writes one or more values (automatically formatted with str
, separated by single spaces) to a given stream, with sys.stdout
being the default. It adds a line break to the end of the written string unless the print
statement ends with a comma.
Examples:
print 'Hello, world!' # Writes 'Hello, world
' to sys.stdout
print 1, 2, 3 # Writes '1 2 3
' to sys.stdout
print >> somefile, 'xyz' # Writes 'xyz' to somefile
print 42, # Writes '42 ' to sys.stdout
The return
statement halts the execution of a function and returns a value. If no value is supplied, None
is returned.
Examples:
return # Returns None from the current function
return 42 # Returns 42 from the current function
return 1, 2, 3 # Returns (1, 2, 3) from the current function
The yield
statement temporarily halts the execution of a generator and yields a value. A generator is a form of iterator and can be used in for
loops, among other things.
Example:
yield 42 # Returns 42 from the current function
The raise
statement raises an exception. It may be used without any arguments (inside an except
clause, to re-raise the currently caught exception), with a subclass of Exception
and an optional argument (in which case, an instance is constructed), or with an instance of a subclass of Exception
.
Examples:
raise # May only be used inside except clauses
raise IndexError
raise IndexError, 'index out of bounds'
raise IndexError('index out of bounds')
The break
statement ends the immediately enclosing loop statement (for
or while
) and continues execution immediately after that loop statement.
Example:
while True:
line = file.readline()
if not line: break
print line
The continue
statement is similar to the break
statement in that it halts the current iteration of the immediately enclosing loop, but instead of ending the loop completely, it continues execution at the beginning of the next iteration.
Example:
while True:
line = file.readline()
if not line: break
if line.isspace(): continue
print line
The import
statement is used to import names (variables bound to functions, classes, or other values) from an external module. This also covers from __future__ import ...
statements for features that will become standard in future versions of Python.
Examples:
import math
from math import sqrt
from math import sqrt as squareroot
from math import *
The global
statement is used to mark a variable as global. It is used in functions to allow statements in the function body to rebind global variables. Using the global
statement is generally considered poor style and should be avoided whenever possible.
Example:
count = 1
def inc():
global count
count += 1
The exec
statement is used to execute strings containing Python statements, optionally with a given global and local namespace (dictionaries).
Examples:
exec 'print "Hello, world!"'
exec 'x = 2' in myglobals, mylocals # ... where myglobals and mylocals are dicts
Compound statements contain groups (blocks) of other statements.
The if
statement is used for conditional execution, and it may include elif
and else
clauses.
Example:
if x < 10:
print 'Less than ten'
elif 10 <= x < 20:
print 'Less than twenty'
else:
print 'Twenty or more'
The while
statement is used for repeated execution (looping) while a given condition is true. It may include an else
clause (which is executed if the loop finishes normally, without any break
or return
statements, for instance).
Example:
x = 1
while x < 100:
x *= 2
print x
The for
statement is used for repeated execution (looping) over the elements of sequences or other iterable objects (objects having an __iter__
method that returns an iterator). It may include an else
clause (which is executed if the loop finishes normally, without any break
or return
statements, for instance).
Example:
for i in range(10, 0, -1):
print i
print 'Ignition!'
The try
statement is used to enclose pieces of code where one or more known exceptions may occur, and enables your program to trap these exceptions and perform exception-handling code if an exception is trapped. The try
statement can combine several except
clauses (handling exceptional circumstances) and finally
clauses (executed no matter what; useful for cleanup).
Example:
try:
1/0
except ZeroDivisionError:
print "Can't divide anything by zero."
finally:
print "Done trying to calculate 1/0"
The with
statement is used to wrap a block of code using a so-called context manager, allowing the context manager to perform some setup and cleanup actions. For example, files can be used as context managers, and they will close themselves as part of the cleanup.
Note In Python 2.5, you need from __future__ import with_statement
for the with
statement to work as described.
Example:
with open("somefile.txt") as myfile:
dosomething(myfile)
# The file will have been closed here
Function definitions are used to create function objects and to bind global or local variables to these function objects.
Example:
def double(x):
return x*2
Class definitions are used to create class objects and to bind global or local variables to these class objects.
Example:
class Doubler:
def __init__(self, value):
self.value = value
def double(self):
self.value *= 2