Python
Python
5 quick
reference
John W. Shipman
2010-05-28 11:51
Abstract
A reference guide to most of the common features of the Python programming language, version
2.5.
This publication is available in Web form1 and also as a PDF document2. Please forward any
comments to tcc-doc@nmt.edu.
Table of Contents
1. Introduction: What is Python? .................................................................................................. 5
2. Starting Python ........................................................................................................................ 5
2.1. Using Python in Windows .............................................................................................. 5
2.2. Using Python in Linux ................................................................................................... 5
3. Line syntax .............................................................................................................................. 6
4. Reserved words ....................................................................................................................... 6
5. Basic types .............................................................................................................................. 6
6. Numeric types ......................................................................................................................... 7
6.1. Type int: Integers ......................................................................................................... 7
6.2. Type long: Extended-precision integers .......................................................................... 8
6.3. Type bool: Boolean truth values .................................................................................... 8
6.4. Type float: Floating-point numbers .............................................................................. 9
6.5. Type complex: Imaginary numbers ............................................................................... 9
7. Sequence types ....................................................................................................................... 10
7.1. Operations common to all the sequence types ................................................................. 10
7.2. Type str: Strings of 8-bit characters .............................................................................. 13
7.2.1. String constants ................................................................................................. 13
7.2.2. The string format operator ................................................................................. 14
7.2.3. String formatting from a dictionary ..................................................................... 16
7.2.4. Definition of “whitespace” ................................................................................. 16
7.2.5. Methods on str values ...................................................................................... 17
7.3. Type unicode: Strings of 32-bit characters .................................................................... 24
7.3.1. The UTF-8 encoding ........................................................................................... 24
7.4. Type list: Mutable sequences ..................................................................................... 25
7.4.1. Methods on lists ................................................................................................. 26
7.4.2. List comprehensions .......................................................................................... 29
7.5. Type tuple: Immutable sequences ............................................................................... 30
8. Types set and frozenset: Set types ...................................................................................... 31
8.1. Operations on mutable and immutable sets ................................................................... 32
1
http://www.nmt.edu/tcc/help/pubs/python25/web/
2
http://www.nmt.edu/tcc/help/pubs/python25/python25.pdf
2. Starting Python
You can use Python in two different ways:
• In “calculator” or “conversational mode”, Python will prompt you for input with three greater-than
signs (>>>). Type a line and Python will print the result. Here's an example:
>>> 2+2
4
>>> 1.0 / 7.0
0.14285714285714285
• You can also use Python to write a program, sometimes called a script.
python
3
http://www.nmt.edu/tcc/help/pubs/lang/pytut/
4
http://www.python.org/
python filename.py
Under Unix, you can also make a script self-executing by placing this line at the top:
#!/usr/local/bin/python
You must also tell Linux that the file is executable by using the command “chmod +x filename”.
For example, if your script is called hello.py, you would type this command:
chmod +x hello.py
3. Line syntax
The comment character is “#”; comments are terminated by end of line.
Long lines may be continued by ending the line with a backslash (\), but this is not necessary if there
is at least one open “(”, “[”, or “{”.
4. Reserved words
and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from,
global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, and yield.
5. Basic types
In programming, you manipulate values using operators. For example, in the expression “1+2”, the ad-
dition operator (+) is operating on the values 1 and 2 to produce the sum, 3. The Python operators are
described in Section 12, “Operators and expressions” (p. 44), but let's look first at Python's way of rep-
resenting values.
Every Python value must have a type. For example, the type of the whole number 1 is int, short for
“integer.”
Here is a table summarizing most of the commonly-used Python types.
6. Numeric types
Python has a number of different types used for representing numbers.
To convert other numbers or character strings to type int, see Section 13.16, “int(): Convert to int
type” (p. 50).
If you perform operations on int values that result in numbers that are too large, Python automatically
converts them to long type; see Section 6.2, “Type long: Extended-precision integers” (p. 8).
To convert a value of a different numeric type or a string of characters to a long value, see Section 13.20,
“long(): Convert to long type” (p. 51).
>>> 2 < 3
True
>>> 3 < 2
False
>>> True+4
5
>>> False * False
0
All other values are considered True. To convert any value to a Boolean, see Section 13.4, “bool():
Convert to Boolean” (p. 46).
>>> 1.0/7.0
0.14285714285714285
>>> -2*-4.2e37
8.4000000000000004e+37
>>> 5j
5j
>>> 1+2.56j
(1+2.5600000000000001j)
>>> (1+2.56j)*(-1-3.44j)
(7.8064-6j)
5
http://en.wikipedia.org/wiki/IEEE_754-1985
>>> a=(1+2.56j)*(-1-3.44j)
>>> a
(7.8064-6j)
>>> a.real
7.8064
>>> a.imag
-6.0
To construct a complex value from two float values, see Section 13.7, “complex(): Convert to
complex type” (p. 47).
7. Sequence types
The next four types described (str, unicode, list and tuple) are collectively referred to as sequence
types.
Each sequence value represents an ordered set in the mathematical sense, that is, a collection of things
in a specific order.
Python distinguishes between mutable and immutable sequences:
• An immutable sequence can be created or destroyed, but the number, sequence, and values of its
elements cannot change.
• The values of a mutable sequence can be changed. Any element can be replaced or deleted, and new
elements can be added at the beginning, the end, or in the middle.
There are four sequence types, but they share most of the same operations.
• Section 7.1, “Operations common to all the sequence types” (p. 10).
• Section 7.2, “Type str: Strings of 8-bit characters” (p. 13) (immutable).
• Section 7.3, “Type unicode: Strings of 32-bit characters” (p. 24) (immutable).
• Section 7.4, “Type list: Mutable sequences” (p. 25) (mutable).
• Section 7.5, “Type tuple: Immutable sequences” (p. 30) (immutable).
S*n
For a sequence S and a positive integer n, the result is a new sequence containing all the elements
of S repeated n times.
>>> 'worra'*8
'worraworraworraworraworraworraworraworra'
>>> [0]*4
[0, 0, 0, 0]
>>> (True, False)*5
(True, False, True, False, True, False, True, False, True, False)
x in S
Is any element of a sequence S equal to x?
For convenience in searching for substrings, if the sequence to be searched is a string, the x operand
can be a multi-character string. In that case, the operation returns True if x is found anywhere in
S.
>>> 1 in [2,4,6,0,8,0]
False
>>> 0 in [2,4,6,0,8,0]
True
>>> 'a' in 'banana'
True
>>> 3.0 in (2.5, 3.0, 3.5)
True
>>> "baz" in "rowrbazzle"
True
x not in S
Are all the elements of a sequence S not equal to x?
S[i]
Subscripting: retrieve the ith element of s, counting from zero. If i is greater than or equal to the
number of elements of S, an IndexError exception is raised.
>>> 'Perth'[0]
'P'
>>> 'Perth'[1]
S[i:j]
Slicing: For a sequence S and two integers i and j, return a new sequence with copies of the elements
of S between positions i and j.
The values used in slicing refer to the positions between elements, where position zero is the position
before the first element; position 1 is between the first and second element; and so on.
You can also specify positions relative to the end of a sequence. Position -1 is the position before
the last element; -2 is the position before the second-to-last element; and so on.
You can omit the starting position to obtain a slice starting at the beginning. You can omit the ending
position to get all the elements through the last.
For example, here is a diagram showing three slices of the string 'abcdef'.
[−6][−5][−4][−3][−2][−1]
a b c d e f
[0] [1] [2] [3] [4] [5] [6]
[2:5]
[:3] [3:]
>>> 'abcdef'[2:5]
'cde'
>>> 'abcdef'[:3]
'abc'
>>> 'abcdef'[3:]
'def'
>>> (90, 91, 92, 93, 94, 95)[2:5]
(92, 93, 94)
S[i:j:k]
You can use a slice expression like this to select every kth element. Examples:
>>> 'Penguin'
'Penguin'
>>> "ha'penny"
"ha'penny"
>>> "Single ' and double\" quotes"
'Single \' and double" quotes'
>>> ''
''
>>> ""
''
>>> s='''This string
... contains two lines.'''
>>> t="""This string
... contains
... three lines."""
Raw strings: If you need to use a lot of backslashes inside a string constant, and doubling them is too
confusing, you can prefix any string with the letter r to suppress the interpretation of escape sequences.
For example, '\\\\' contains two backslashes, but r'\\\\' contains four. Raw strings are particularly
useful with Section 21.5, “re: Regular expression pattern-matching” (p. 117).
f % v
where f is the template string and v specifies the value or values to be formatted using that template.
If multiple values are to be formatted, v must be a tuple.
The template string may contain any mixture of ordinary text and format codes. A format code always
starts with a percent (%) symbol. See Table 4, “Format codes” (p. 15).
The result of a format operation consists of the ordinary characters from the template with values sub-
stituted within them wherever a format code occurs. A conversational example:
In the above example, there are two format codes. Code “%d” means “substitute a decimal number
here,” and code “%s” means “substitute a string value here”. The number 49 is substituted for the first
format code, and the string "kiwis" replaces the second format code.
In general, format codes have this form:
%[p][m[.n]]c
Here are the format type codes, c in the general expression above:
f % D
%(k)[p][m[.n]]c
where k is a key in dictionary D, and the rest of the format code is as in the usual string format operator.
For each format code, the value of D[k] is used. Example:
6
http://en.wikipedia.org/wiki/ASCII
S.center(w)
Return S centered in a string of width w, padded with spaces. If w<=len(S), the result is a copy of
S. If the number of spaces of padding is odd, the extra space will placed after the centered value.
Example:
>>> 'x'.center(4)
' x '
S.count(t[,start[,end]])
Return the number of times string t occurs in S. To search only a slice S[start:end] of S, supply
start and end arguments.
>>> 'banana'.count('a')
3
>>> 'bananana'.count('na')
3
>>> 'banana'.count('a', 3)
2
>>> 'banana'.count('a', 3, 5)
1
S.decode ( encoding )
If S contains an encoded Unicode string, this method will return the corresponding value as unicode
type. The encoding argument specifies which decoder to use; typically this will be the string
'utf_8' for the UTF-8 encoding. For discussion and examples, see Section 7.3.1, “The UTF-8 en-
coding” (p. 24).
S.endswith(t[,start[,end]])
Predicate to test whether S ends with string t. If you supply the optional start and end arguments,
it tests whether the slice S[start:end] ends with t.
>>> 'bishop'.endswith('shop')
True
>>> 'bishop'.endswith('bath and wells')
False
>>> 'bishop'[3:5]
6
http://en.wikipedia.org/wiki/ASCII
S.expandtabs([tabsize])
Returns a copy of S with all tabs replaced by one or more spaces. Each tab is interpreted as a request
to move to the next “tab stop”. The optional tabsize argument specifies the number of spaces
between tab stops; the default is 8.
Here is how the function actually works. The characters of S are copied to a new string T one at a
time. If the character is a tab, it is replaced by enough tabs so the new length of T is a multiple of
the tab size (but always at least one space).
>>> 'X\tY\tZ'.expandtabs()
'X Y Z'
>>> 'X\tY\tZ'.expandtabs(4)
'X Y Z'
>>> 'a\tbb\tccc\tdddd\teeeee\tfffff'.expandtabs(4)
'a bb ccc dddd eeeee fffff'
S.find(t[,start[,end]])
If string t is not found in S, return -1; otherwise return the index of the first position in S that
matches t.
The optional start and end arguments restrict the search to slice S[start:end].
>>> 'banana'.find('an')
1
>>> 'banana'.find('ape')
-1
>>> 'banana'.find('n', 3)
4
>>> 'council'.find('c', 1, 4)
-1
S.index(t[,start[,end]])
Works like .find(), but if t is not found, it raises a ValueError exception.
>>> 'council'.index('co')
0
>>> 'council'.index('phd')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
S.isalnum()
Predicate that tests whether S is nonempty and all its characters are alphanumeric.
>>> ''.isalnum()
False
>>> 'abc123'.isalnum()
True
>>> '&*$#&*()abc123'.isalnum()
False
>>> 'abc123'.isalpha()
False
>>> 'MaryRecruiting'.isalpha()
True
>>> ''.isalpha()
False
S.isdigit()
Predicate that tests whether S is nonempty and all its characters are digits.
>>> 'abc123'.isdigit()
False
>>> ''.isdigit()
False
>>> '2415'.isdigit()
True
S.islower()
Predicate that tests whether S is nonempty and all its letters are lowercase (non-letter characters
are ignored).
>>> ''.islower()
False
>>> 'abc123'.islower()
True
>>> 'ABC123'.islower()
False
S.isspace()
Predicate that tests whether S is nonempty and all its characters are whitespace characters.
>>> ''.isspace()
False
>>> ' \t\n\r'.isspace()
True
>>> 'killer \t \n rabbit'.isspace()
False
S.istitle()
A predicate that tests whether S has “title case”. In a title-cased string, uppercase characters
may appear only at the beginning of the string or after some character that is not a letter. Lowercase
characters may appear only after an uppercase letter.
S.isupper()
Predicate that tests whether S is nonempty and all its letters are uppercase letters (non-letter char-
acters are ignored).
S.join(L)
L must be a sequence of strings. The returned value is a string containing the members of the sequence
with copies of the delimiter string S inserted between them.
One quite common operation is to use the empty string as the delimiter to concatenate the elements
of a sequence.
Examples:
S.ljust(w)
Return a copy of S left-justified in a field of width w, padded with spaces. If w<=len(S), the result
is a copy of S.
>>> "Ni".ljust(4)
'Ni '
S.lower()
Returns a copy of S with all uppercase letters replaced by their lowercase equivalent.
S.lstrip([c])
Return S with all leading characters from string c removed. The default value for c is a string con-
taining all the whitespace characters.
S.partition(d)
Searches string S for the first occurrence of some delimiter string d. If S contains the delimiter, it
returns a tuple (pre, d, post), where pre is the part of S before the delimiter, d is the delimiter
itself, and post is the part of S after the delimiter.
If the delimiter is not found, this method returns a 3-tuple (S, '', '').
S.replace(old,new[,max])
Return a copy of S with all occurrences of string old replaced by string new. Normally, all occur-
rences are replaced; if you want to limit the number of replacements, pass that limit as the max ar-
gument.
S.rfind(t[,start[,end]])
Like .find(), but if t occurs in S, this method returns the highest starting index.
>>> 'banana'.find('a')
1
>>> 'banana'.rfind('a')
5
S.rindex(t[,start[,end]])
Similar to S.index(), but it returns the last index in S where string t is found. It will raise a
ValueError exception if the string is not found.
S.rjust(w[,fill])
Return a copy of S right-justified in a field of width w, padded with spaces. If w<=len(S), the result
is a copy of S.
To pad values with some character other than a space, pass that character as the optional second
argument.
>>> '123'.rjust(5)
' 123'
>>> '123'.rjust(5,'*')
'**123'
S.rpartition(d)
Similar to S.partition(), except that it finds the last occurrence of the delimiter.
S.rsplit(d[,max])
Similar to S.split(d[,max]), except that if there are more fields than max, the split fields are
taken from the end of the string instead of from the beginning.
S.rstrip([c])
Return S with all trailing characters from string c removed. The default value for c is a string con-
taining all the whitespace characters.
S.split([d[,max]])
Returns a list of strings [s0, s1, ...] made by splitting S into pieces wherever the delimiter
string d is found. The default is to split up S into pieces wherever clumps of one or more whitespace
characters are found.
The optional max argument limits the number of pieces removed from the front of S. The resulting
list will have no more than max+1 elements.
To use the max argument while splitting the string on clumps of whitespace, pass None as the first
argument.
>>> 'a/b/c/d/e'.split('/', 2)
['a', 'b', 'c/d/e']
>>> 'a/b'.split('/', 2)
['a', 'b']
>>> "I am Zoot's identical twin sister, Dingo.".split(None, 2)
['I', 'am', "Zoot's identical twin sister, Dingo."]
S.splitlines([keepends])
Splits S into lines and returns a list of the lines as strings. Discards the line separators unless the
optional keepends arguments is true.
S.startswith(t[,start[,end]])
Predicate to test whether S starts with string t. Otherwise similar to .endswith().
>>> "bishop".startswith('bish')
True
>>> "bishop".startswith('The')
False
S.strip([c])
Return S with all leading and trailing characters from string c removed. The default value for c is
a string containing all the whitespace characters.
S.swapcase()
Return a copy of S with each lowercase character replaced by its uppercase equivalent, and vice
versa.
>>> "abcDEF".swapcase()
'ABCdef'
S.title()
Returns the characters of S, except that the first letter of each word is uppercased, and other letters
are lowercased.
S.translate(new[,drop])
This function is used to translate or remove each character of S. The new argument is a string of
exactly 256 characters, and each character x of the result is replaced by new[ord(x)].
If you would like certain characters removed from S before the translation, provide a string of those
characters as the drop argument.
For your convenience in building the special 256-character strings used here, see the definition of
the maketrans() function of Section 21.2, “string: Utility functions for strings” (p. 113), where
you will find examples.
S.upper()
Return a copy of S with all lowercase characters replaced by their uppercase equivalents.
S.zfill(w)
Return a copy of S left-filled with '0' characters to width w.
>>> '12'.zfill(9)
'000000012'
u'klarn'
Examples:
>>> u'Klarn.'
u'Klarn.'
>>> u'Non-breaking-\xa0-space.'
u'Non-breaking-\xa0-space.'
>>> u'Less-than-or-equal symbol: \u2264'
u'Less-than-or-equal symbol: \u2264'
>>> u"Phoenician letter 'wau': \U00010905"
u"Phoenician letter 'wau': \U00010905"
>>> len(u'\U00010905')
1
All the operators and methods of str type are available with unicode values.
Additionally, for a Unicode value U, use this method to encode its value as a string of type str:
U.encode ( encoding )
Return the value of U as type str. The encoding argument is a string that specifies the encoding
method. In most cases, this will be 'utf_8'. For discussion and examples, see Section 7.3.1, “The
UTF-8 encoding” (p. 24).
7
http://www.unicode.org/
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 x x x x x x x 7x 0 x x x x x x x
0 0 0 0 0 0 0 0 0 0 0 0 0 y y y y y z z z z z z 5y 6z 1 1 0 y y y y y 1 0 z z z z z z
0 0 0 0 0 0 0 0 x x x x y y y y y y z z z z z z 4x 6y 6z 1 1 1 0 x x x x 1 0 y y y y y y 1 0 z z z z z z
0 0 0 www x x x x x x y y y y y y z z z z z z 3w 6x 6y 6z 1 1 1 1 0 www 1 0 x x x x x x 1 0 y y y y y y 1 0 z z z z z z
U.encode('utf_8')
To decode a regular str value S that contains a UTF-8 encoded value, use this method:
S.decode('utf_8')
Examples:
>>> tilde='~'
>>> tilde.encode('utf_8')
'~'
>>> u16 = u'\u0456'
>>> s = u16.encode('utf_8')
>>> s
'\xd1\x96'
>>> s.decode('utf_8')
u'\u0456'
>>> u32 = u'\U000E1234'
>>> s = u32.encode('utf_8')
>>> s
'\xf3\xa1\x88\xb4'
>>> s.decode('utf_8')
u'\U000e1234'
UTF-8 is not the only encoding method. For more details, consult the documentation for the Python
module codecs8.
8
http://docs.python.org/lib/module-codecs.html
You can also create a list by performing specific operations on each element of some sequence; see Sec-
tion 7.4.2, “List comprehensions” (p. 29).
Lists support all the operations described under Section 7.1, “Operations common to all the sequence
types” (p. 10). Methods available on lists are discussed in Section 7.4.1, “Methods on lists” (p. 26).
There are a number of functions that can be used with lists as well:
• Section 13.2, “all(): Are all the elements of a sequence true?” (p. 45).
• Section 13.3, “any(): Are any of the members of a sequence true?” (p. 45).
• Section 13.6, “cmp(): Compare two values” (p. 46).
• Section 13.10, “enumerate(): Step through indices and values of a sequence” (p. 48)
• Section 13.12, “filter(): Extract qualifying elements from a sequence” (p. 48).
• Section 13.17, “iter(): Produce an iterator over a sequence” (p. 50).
• Section 13.18, “len(): Number of elements” (p. 50).
• Section 13.19, “list(): Convert to a list” (p. 51).
• Section 13.21, “map(): Apply a function to each element of a sequence” (p. 51).
• Section 13.22, “max(): Largest element of a sequence” (p. 51).
• Section 13.23, “min(): Smallest element of a sequence” (p. 52).
• Section 13.28, “range(): Generate an arithmetic progression as a list” (p. 53).
• Section 13.30, “reduce(): Sequence reduction” (p. 54).
• Section 13.31, “reversed(): Produce a reverse iterator” (p. 54).
• Section 13.34, “sorted(): Sort a sequence” (p. 56).
• Section 13.36, “sum(): Total the elements of a sequence” (p. 57).
• Section 13.41, “xrange(): Arithmetic progression generator” (p. 58).
• Section 13.42, “zip(): Combine multiple sequences” (p. 59).
L.count(x)
Return the number of elements of L that compare equal to x.
L.extend(S)
Append another sequence S to L.
>>> colors
['red', 'green', 'blue', 'indigo', 'violet', 'pale puce']
>>> colors.index('blue')
2
>>> colors.index('taupe')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.index(x): x not in list
>>> M=[0, 0, 3, 0, 0, 3, 3, 0, 0, 3]
>>> M.index(3)
2
>>> M.index(3, 4, 8)
5
>>> M.index(3, 0, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.index(x): x not in list
L.insert(i,x)
Insert a new element x into list L just before the ith element, shifting all higher-number elements
to the right. No value is returned.
>>> colors
['red', 'green', 'blue', 'indigo', 'violet', 'pale puce']
>>> colors[1]
'green'
>>> colors.insert(1, "yellow")
>>> colors
['red', 'yellow', 'green', 'blue', 'indigo', 'violet', 'pale puce']
L.pop([i])
Remove and return the element with index i from L. The default value for i is -1, so if you pass no
argument, the last element is removed.
>>> colors
['red', 'yellow', 'green', 'blue', 'indigo', 'violet', 'pale puce']
>>> tos = colors.pop()
>>> tos
'pale puce'
>>> colors
['red', 'yellow', 'green', 'blue', 'indigo', 'violet']
>>> colors[4]
L.remove(x)
Remove the first element of L that is equal to x. If there aren't any such elements, raises ValueError.
>>> colors
['red', 'yellow', 'green', 'blue', 'violet']
>>> colors.remove('yellow')
>>> colors
['red', 'green', 'blue', 'violet']
>>> colors.remove('cornflower')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> notMuch = [0, 0, 3, 0]
>>> notMuch.remove(0)
>>> notMuch
[0, 3, 0]
>>> notMuch.remove(0)
>>> notMuch
[3, 0]
>>> notMuch.remove(0)
>>> notMuch
[3]
>>> notMuch.remove(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
L.reverse()
Reverses the elements of L in place. Does not return a result. Compare Section 13.31, “reversed():
Produce a reverse iterator” (p. 54).
>>> colors
['red', 'green', 'blue', 'violet']
>>> colors.reverse()
>>> colors
['violet', 'blue', 'green', 'red']
L.sort(cmp[,key[,reverse]]])
Sort list L in place. Does not return a result. Compare Section 13.34, “sorted(): Sort a se-
quence” (p. 56).
The reordering is guaranteed to be stable—that is, if two elements are considered equal, their order
after sorting will not change.
While sorting, Python will use the built-in cmp() function to compare elements; see Section 13.6,
“cmp(): Compare two values” (p. 46). You may provide, as the first argument to the .sort()
method, your own comparator function to compare elements. This function must have the same
calling sequence and return value convention as the built-in cmp() function: it must take two argu-
>>> temps=[67, 73, 85, 93, 92, 78, 95, 100, 104]
>>> temps.sort()
>>> temps
[67, 73, 78, 85, 92, 93, 95, 100, 104]
>>> def reverser(n1, n2):
... '''Comparison function to use reverse order.
... '''
... return cmp(n2, n1)
...
>>> temps.sort(reverser)
>>> temps
[104, 100, 95, 93, 92, 85, 78, 73, 67]
>>> def unitsDigit(n):
... '''Returns only the units digit of n.
... '''
... return n % 10
...
>>> temps.sort(None, unitsDigit)
>>> temps
[100, 92, 93, 73, 104, 95, 85, 67, 78]
>>> temps.sort(None, None, True)
>>> temps
[104, 100, 95, 93, 92, 85, 78, 73, 67]
[ e
for v1 in s1
for v2 in s2
...
if c ]
where e is some expression, followed by one or more for clauses, optionally followed by an if clause.
The result is a list containing all the values of expression e after all the nested for loops have been run;
the for loops have the same structure as in Section 16.4, “The for statement: Iteration over a se-
quence” (p. 79). If there is an “if” clause, it determines which values of e are added to the list: if the
if condition is true, the value is added, otherwise it is not added.
This is perhaps easiest to explain with a few examples. In the first example, we construct a list containing
the cubes of the numbers from 1 to 10, inclusive. The for loop generates the numbers 1, 2, ..., 10, and
then the expression “x**3” cubes each one and appends it to the resulting list.
In the next example, we use two for loops. The outer loop generates the sequence [1, 2, 3], and
the inner loop generates the sequence [50, 51]. The expression “x*1000 + y” is computed for each
of the resulting six value sets for x and y, and the result is appended to the list being built.
>>> [ x*1000 + y
... for x in range(1,4)
... for y in range(50, 52) ]
[1050, 1051, 2050, 2051, 3050, 3051]
In the next example, there are two nested loops, each generating the sequence [0, 1, 2]. For each of
the nine trips through the inner loop, we test the values of x and y and discard the cases where they
are equal. The expression “(y, x)” combines the two values into a 2-tuple.
>>> [ (y, x)
... for y in range(3)
... for x in range(3)
... if x != y ]
[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
• Values of type tuple are immutable. Once you have assembled a tuple, you cannot add or delete
elements or change the value of an element inside the tuple.
(value,)
That is, you must provide a comma before the closing “)”, in order to show that it is a tuple, and not
just a parenthesized expression. Note especially the last two examples below:
>>> ()
()
>>> ('farcical', 'aquatic', 'ceremony')
('farcical', 'aquatic', 'ceremony')
>>> ('Ni',)
('Ni',)
>>> ('Ni')
'Ni'
You may also convert an existing sequence of another type using Section 13.37, “tuple(): Convert to
a tuple” (p. 57).
The tuple type does not have comprehensions (see Section 7.4.2, “List comprehensions” (p. 29)), but
you can get the equivalent by applying the tuple() function to a list comprehension. Here is an example:
>>> 1 in set([0,1,4])
True
>>> 99 in set([0,1,4])
False
x not in S
Predicate that tests whether element x is not a member of set S.
S1 == S2
Predicate that tests whether sets S1 and S2 have exactly the same members.
S1 != S2
Predicate that tests whether sets S1 and S2 have different members.
S1 > S2
Predicate that tests whether S1 is a proper superset of S2; that is, all the elements of S2 are also
members of S1, but there is at least one element of S1 that is not in S2.
S.copy()
Return a new set of the same type as S, containing all the same elements.
>>> s1=set('aeiou')
>>> s2=s1
>>> s3=s1.copy()
>>> s1.add('y')
>>> s1
set(['a', 'e', 'i', 'o', 'u', 'y'])
>>> s2
set(['a', 'e', 'i', 'o', 'u', 'y'])
>>> s3
set(['a', 'i', 'e', 'u', 'o'])
S1.difference(S2)
Returns a new set of the same type as S1, containing only those values found in S1 but not found
in S2. The S2 argument may be a set or a sequence.
>>> set('roygbiv').difference('rgb')
set(['i', 'o', 'v', 'y'])
S1 - S2
Same as S1.difference(S2), except that S2 must be a set.
S1.intersection(S2)
Returns a new set, of the same type as S1, containing only the elements found both in S1 and S2.
S2 may be a set or a sequence.
>>> set([1,2,3,5,7,11]).intersection(set([1,3,5,7,9]))
set([1, 3, 5, 7])
>>> set([1,3,5]).intersection( (2,4,6,8) )
set([])
>>> set([1,2]).issubset(set([2,4,1,8]))
True
>>> set([2,4,1,8]).issubset(set([1,2]))
False
>>> set(['r', 'g', 'b']) <= set(['r', 'o', 'y', 'g', 'b', 'i', 'v'])
True
S1 <= S2
Same as S1.issubset(S2), but S2 must be a set.
S1.issuperset(S2)
Predicate that tests whether every element of S2 is also in S1. S2 may be a set or a sequence.
>>> set([1,2]).issuperset(set([2,4,1,8]))
False
>>> set([2,4,1,8]).issuperset(set([1,2]))
True
S1 >= S2
Same as S1.issuperset(S2).
S1.symmetric_difference(S2)
Returns a new set of the same type as S1, containing only elements found in S1 or S2, but not found
in both. The S2 argument may be a set or a sequence.
>>> set('aeiou').symmetric_difference('etaoin')
set(['n', 'u', 't'])
S1 ^ S2
Same as S1.symmetric_difference(S2), but S2 must be a set.
S1.union(S2)
Returns a new set, with the same type as S1, containing all the elements found in either S1 or S2.
The S2 argument may be a set or a sequence.
>>> set([1,2]).union(set([1,3,7]))
set([1, 2, 3, 7])
>>> set([1,2]).union( (8,2,4,5) )
set([8, 1, 2, 4, 5])
S1 | S2
Same as S1.union(S2).
S.clear()
Remove all the elements from set S.
>>> pbr
set(['Brazil', 'USA'])
>>> pbr.clear()
>>> pbr
set([])
S.discard(x)
If set S contains element x, remove that element from S.
If x is not in S, it is not considered an error; compare S.remove(x).
>>> pbr
set(['Brazil', 'Australia', 'USA'])
>>> pbr.discard('Swaziland')
>>> pbr
set(['Brazil', 'Australia', 'USA'])
>>> pbr.discard('Australia')
>>> pbr
set(['Brazil', 'USA'])
S1.difference_update(S2)
Modify set S1 by removing any values found in S2. Value S2 may be a set or a sequence.
>>> s1=set('roygbiv')
>>> s1.difference_update('rgb')
>>> s1
set(['i', 'o', 'v', 'y'])
S1 -= S2
Same as S1.difference_update(S2), but S2 must be a set.
S1.intersection_update(S2)
Modify set S1 so that it contains only values found in both S1 and S2.
>>> s1=set('roygbiv')
>>> s1
set(['b', 'g', 'i', 'o', 'r', 'v', 'y'])
>>> s1.intersection_update('roy')
>>> s1
set(['y', 'r', 'o'])
S1 &= S2
Same as S1.intersection_update(S2), but S2 must be a set.
>>> pbr
set(['Brazil', 'Canada', 'Australia', 'USA'])
>>> pbr.remove('Canada')
>>> pbr
set(['Brazil', 'Australia', 'USA'])
>>> pbr.remove('Swaziland')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Swaziland'
S1.symmetric_difference_update(S2)
Remove from S1 any elements found in both S1 and S2. Value S2 may be a set or a sequence.
>>> s1=set('abcd')
>>> s1.symmetric_difference_update('cdefg')
>>> s1
set(['a', 'b', 'e', 'g', 'f'])
S1 ^= S2
Same as S1.symmetric_difference_update(S2), but S2 must be a set.
S1.update(S2)
Add to S1 any elements of S2 not found in S1. The S2 argument may be a set or a sequence.
>>> s1=set('rgb')
>>> s1
set(['r', 'b', 'g'])
>>> s1.update('roygbiv')
>>> s1
set(['b', 'g', 'i', 'o', 'r', 'v', 'y'])
S1 |= S2
Same as S1.update(S2), but S2 must be a set.
There can be any number of key-value pairs (including zero). Each key-value has the form “ki:vi”,
and pairs are separated by commas. Here are some examples of dictionaries:
{}
{'Bolton': 'Notlob', 'Ipswich': 'Esher'}
{(1,1):48, (8,20): 52}
For efficiency reasons, the order of the pairs in a dictionary is arbitrary: it is essentially an unordered
set of ordered pairs. If you display a dictionary, the pairs may be shown in a different order than you
used when you created it.
D[k] = v
If dictionary D does not have a key-value pair whose key equals k, a new pair is added with key k
and value v.
If D already has a key-value pair whose key equals k, the value of that pair is replaced by v.
k in D
A predicate that tests whether D has a key equal to k.
k not in D
A predicate that tests whether D does not have a key equal to k.
del D[k]
In Python, del is a statement, not a function; see Section 15.3, “The del statement: Delete a name
or part of a value” (p. 73).
If dictionary D has a key-value pair whose key equals k, that key-value pair is deleted from D. If
there is no matching key-value pair, the statement will raise a KeyError exception.
D.get(k, x)
If dictionary D has a key equal to x, it returns the corresponding value, that is, it is the same as the
expression “D[x]”.
However, if D has no key-value pair for key k, this method returns the default value x. The second
argument is optional; if omitted, and D has no key equal to k, it returns None.
D.has_key(k)
A predicate that returns True if D has a key k.
D.items()
Returns the contents of dictionary D as a list of two-element tuples (k, v), in no particular order.
D.iterkeys()
Returns an iterator that generates the keys from dictionary D. See Section 17.2, “Iterators: Values
that can produce a sequence of values” (p. 88).
D.itervalues()
Returns an iterator that generates the values from dictionary D. See Section 17.2, “Iterators: Values
that can produce a sequence of values” (p. 88).
D.keys()
Returns a list of the key values in dictionary D, in no particular order.
D.popitem()
Returns an arbitrary entry from dictionary D as a (key, value) tuple, and also removes that entry.
If D is empty, raises a KeyError exception.
D.setdefault(k, x)
If dictionary D has a key equal to k, this method returns the corresponding value D[k].
D.update(D2)
Merge the contents of dictionary D2 into dictionary D. For any key-value pairs that have the same
key in both D and D2, the value for that key in D after this operation will be the value from D2, not
the value from D.
f = open(name[,mode[,bufsize]]])
name
The path name of the file to be opened, as a string.
mode
An optional string specifying what you plan to do with the file. If omitted, you will get read access
to the file. In general the value consists of three parts:
• General mode, one of:
r Read access. The file must already exist. You will not be allowed to write to it.
w Write access. If there is no file by this name, a new one will be created.
Important
If there is an existing file, it will be deleted!
a Append access. If there is a file by this name, your initial position will be at the end of the file,
and you will be allowed to write (and read). If there is no file by this name, a new one will be
The variable line will be set to each line of the file in turn. The line terminator character (if any) will
be present in that string.
Other aspects of files:
• Every open file has a current position. Initially, this will 0L if you opened it for reading or writing, or
the size of the file if you opened it with append access. Each write or read operation moves this position
by the amount read or written. You can also query or set the file position; see Section 10.1, “Methods
on file objects” (p. 42).
• Files may use a technique called buffering. Because physical access to some storage media (such as
disk drives) takes a relatively long time, Python may employ a storage area called a buffer as a holding
area for data being input or output.
f.seek(-4, 2)
F.tell()
This method returns the current file position relative to the beginning as a long value.
F.truncate([pos])
Remove any contents of F past position pos, which defaults to the current position.
F.write(s)
Write the contents of string s to file F. This operation will not add terminator characters; if you
want newlines in your file, include them in the string s.
F.writelines(S)
For a sequence S containing strings, write all those strings to F. No line terminators will be added;
you must provide them explicitly if you want them.
>>> x = None
>>> x
>>> print x
None
The value None is returned from any function that executes a return statement with no value, or any
function after it executes its last line if that last line is not a return statement.
abs(x)
>>> abs(-33)
33
>>> abs(33)
33
>>> abs(0)
0
>>> abs(complex(1,5))
5.0990195135927845
>>> bool(0)
False
>>> bool(0.0)
False
>>> bool(0L)
False
>>> bool(0j)
False
>>> bool('')
False
>>> bool([])
False
>>> bool(())
False
>>> bool({})
False
>>> bool(None)
False
>>> bool(1)
True
>>> bool(15.9)
True
>>> bool([0])
True
>>> bool((None,))
True
>>> bool({None: False})
True
>>> chr(65)
'A'
>>> chr(0)
'\x00'
cmp(x, y)
The built-in cmp() function will typically return only the values -1, 0, or 1. However, there are other
places that expect functions with the same calling sequence, and those functions may return other values.
It is best to observe only the sign of the result.
>>> cmp(2,5)
-1
>>> cmp(5,5)
0
>>> cmp(5,2)
1
>>> cmp('aardvark', 'aardwolf')
-1
complex(R, I)
Example:
That is, there may be one optional positional argument or any number of keyword arguments.
• If you supply no arguments, you get a new, empty dictionary.
• If a positional argument is supplied, it must be a sequence of two-element sequences. Each two-element
sequence becomes one key-value pair of the result.
>>> dict()
{}
>>> dict ( [ (0, 'stop'), (1, 'go') ] )
{0: 'stop', 1: 'go'}
>>> dict((('y', 'boy'), ('x', 'girl')))
{'y': 'boy', 'x': 'girl'}
• If you supply any keyword arguments, each keyword becomes a key in the resulting dictionary, and
that argument's value becomes the corresponding value of that key-value pair.
divmod(x, y)
Examples:
>>> divmod(13, 5)
(2, 3)
>>> divmod(1.6, 0.5)
(3.0, 0.10000000000000009)
filter(f, S)
The filtering function f is the first argument. It is applied to every element of some sequence S. The
result is a new sequence of the same type as S, containing only those elements x of S for which f(x)
returned True.
>>> float()
0.0
>>> float(17)
17.0
>>> float(' 3.1415 ')
3.1415000000000002
>>> print float('6.0221418e23')
6.0221418e+23
>>> float('142x')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): 142x
frozenset()
frozenset(S)
The first form creates an empty frozenset. To convert an existing sequence value S to a frozenset,
use the second form.
>>> frozenset()
frozenset([])
>>> frozenset('aeiou')
frozenset(['a', 'i', 'e', 'u', 'o'])
>>> frozenset([0, 0, 0, 44, 0, 44, 18])
frozenset([0, 18, 44])
For more information, see Section 8, “Types set and frozenset: Set types” (p. 31).
int(ns)
where ns is the value to be converted. If ns is a float, the value will be truncated, discarding the
fraction.
If you want to convert a character string s to an int, and that string is not a decimal number, use this
form, where b is an integer in the range [2, 36] that specifies the base (radix).
int(s, b)
Examples:
>>> int(43L)
43
>>> int(True)
1
>>> int(False)
0
>>> int(43.89)
43
>>> int("69")
69
>>> int('77', 8)
63
>>> int('7ff', 16)
2047
>>> int('10101', 2)
21
>>> long(43)
43L
>>> long(43.889)
43L
>>> long('12345678901234567890123457890')
12345678901234567890123457890L
>>> long('potrzebie456', 36)
3381314581245790842L
>>> min('blimey')
'b'
>>> min ( [-505, -575, -144, -288] )
-575
>>> oct(0)
'0'
>>> oct(127)
'0177'
>>> ord('A')
65
>>> ord('\x00')
0
pow(x, y)
y
For integer arithmetic, the function also has a three-argument form that computes x %z, but more effi-
ciently than if you used that expression:
pow(x, y, z)
>>> 2**4
16
>>> pow(2,4)
16
>>> pow(2.5, 4.5)
61.763235550163657
>>> (2**9)%3
2
>>> pow(2,9,3)
2
>>> range(4)
[0, 1, 2, 3]
>>> range(4,9)
[4, 5, 6, 7, 8]
>>> range(10,104,10)
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> range(5,-1,-1)
[5, 4, 3, 2, 1, 0]
raw_input(p)
The argument p is a prompt string that is written to standard output. Then a line is read from standard
input and returned as a string, without its trailing newline character.
reduce(f, S)
reduce(f, S, I)
The result depends on the number of elements in S, and whether the initial value I is supplied. Let's
look first at the case where argument I is not supplied.
• If S has only one element, the result is S[0].
• If S has two elements, the result is f(S[0], S[1]).
• If S has three elements, the result is f(f(S[0], S[1]), S[2]).
• If S has four or more elements, f is applied first to S[0] and S[1], then to that result and S[2], and
so on until all elements are reduced to a single value.
If an initial value I is provided, the result is the same as reduce(f, [I]+list(S)).
Some examples:
>>> L=[22,44,88]
>>> backL = reversed(L)
>>> for i in backL:
... print i,
round(x)
The value is returned as a float. In the case that the fractional part of x is exactly one-half, the returned
value is the integer farther from zero. Examples:
You can also provide an optional second argument that specifies how many digits to preserve after the
decimal.
set()
set(S)
When called with no arguments, this function returns a new, empty set. To build a set from an existing
sequence S, use the second form. Examples:
For more information about sets, see Section 8, “Types set and frozenset: Set types” (p. 31).
The cmp, key, and reverse arguments are optional, and have the same meaning as in the .sort()
method of the list type (see Section 7.4.1, “Methods on lists” (p. 26)).
In the first example above, 'Zoe' precedes 'clue', because all uppercase letters are considered to be
less than all lowercase letters. The second example shows how to sort strings as if they were all uppercase.
Note in the last line that the original list L is unchanged.
str(x)
For example:
>>> str(17)
'17'
>>> str({'boy': 'Relmond', 'girl': 'Wirdley'})
"{'boy': 'Relmond', 'girl': 'Wirdley'}"
sum(S)
sum(S, I)
In the second form, the summing process starts with the initial value I. Examples:
>>> L=[1,2,3,4]
>>> sum(L)
10
>>> sum(L,1000)
1010
>>> sum((), 1000)
1000
tuple(s)
The result will be a new tuple with the same elements as S in the same order.
To create an empty tuple, omit the argument. Examples:
>>> tuple()
()
>>> tuple ( ['swallow', 'coconut'] )
('swallow', 'coconut')
>>> tuple ( 'shrubbery' )
('s', 'h', 'r', 'u', 'b', 'b', 'e', 'r', 'y')
>>> tuple ( ['singleton'] )
('singleton',)
>>> type(i)
<type 'int'>
>>> type(i) is int
True
>>> type([2,4,8]) is list
True
>>> unichr(0)
u'\x00'
>>> unichr(ord('A'))
u'A'
>>> unichr(0x3046)
u'\u3046'
>>> unichr(0xe0047)
u'\U000e0047'
>>> unicode('Groucestel')
u'Groucestel'
>>> unicode()
u''
>>> L1=[1,2,3,4]
>>> L2=['a', 'b', 'c', 'd']
>>> zip(L1, L2)
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
>>> L3=[10.0, 20.0, 30.0, 40.0]
>>> zip(L1, L2, L3)
[(1, 'a', 10.0), (2, 'b', 20.0), (3, 'c', 30.0), (4, 'd', 40.0)]
isinstance(s, basestring)
See Section 14.12, “isinstance(): Is a value an instance of some class or type?” (p. 63).
callable(x)
Class names can be called to create an instance of the class. Instances can be called if they define a
.__call__() special method; see Section 19.3.5, “__call__(): What to do when someone calls an
instance” (p. 105).
@classmethod
def methodName(cls, ...):
method body
• In some older versions of Python without the decorator syntax, you can still declare a class method
by placing a line after the method definition, at the same indentation level as the method's def
statement, having this form:
methodName = classmethod(methodName)
delattr(I, A)
For example, if an instance seabiscuit has a rider attribute, this statement would delete that attribute:
delattr(seabiscuit, 'rider')
If the instance has no such attribute, this function will raise an AttributeError exception.
>>> dir()
['__builtins__', '__doc__', '__name__']
>>> x=5; forkTail='Tyrannus'
>>> dir()
['__builtins__', '__doc__', '__name__', 'forkTail', 'x']
>>> print __doc__
>>> cent=100
>>> eval('cent**3')
1000000
execfile(F)
The function returns None. For additional features that allow you to control the environment of the
executed statements, see the official documentation10.
>>> class C:
... def __init__(self, flavor):
... self.flavor = flavor
...
>>> c=C('garlicky')
>>> getattr(c, 'flavor')
'garlicky'
>>> getattr(c, 'aroma', 'bland')
'bland'
>>> getattr(c, 'aroma')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: C instance has no attribute 'aroma'
9
http://docs.python.org/lib/built-in-funcs.html
10
http://docs.python.org/lib/built-in-funcs.html
The special name __builtins__ is bound to a module; name __name__ is bound to the string
'__main__'; and __doc__ is bound to None. Note that defining a new name adds an entry to the
result of globals().
hasattr(I, s)
If this function returns True, you can be sure that the instance has an attribute named s. However, if
it returns False, attempts to access an attribute may still succeed, if the class provides dynamic attributes;
see Section 19.3.11, “__getattr__(): Handle a reference to an unknown attribute” (p. 106). Example:
>>> class C:
... def __init__(self, disc):
... self.disk = disc
...
>>> c=C('five')
>>> hasattr(c, 'disk')
True
>>> hasattr(c, 'disc')
False
>>> hasattr(c, 'jukebox')
False
>>> c.jukebox = 'Nine'
>>> hasattr(c, 'jukebox')
True
>>> i = 20
>>> id(i)
137727456
isinstance(I, C)
issubclass(C1, C2)
Examples:
For related functions, see Section 14.5, “dir(): Display a namespace's names” (p. 60) and Section 14.9,
“globals(): Dictionary of global name bindings” (p. 62).
class C(...):
def R(self):
...read method...
def W(self, value):
...write method...
def D(self):
...delete method...
p = property(R, W, D, doc)
...
where:
• R is a method that takes no arguments and returns the effective attribute value. If omitted, any attempt
to read that attribute will raise AttributeError.
• W is a method that takes one argument and sets the attribute to that argument's value. If omitted, any
attempt to write that attribute will raise AttributeError.
• D is a method that deletes the attribute. If omitted, any attempt to delete that attribute will raise At-
tributeError.
• doc is a documentation string that describes the attribute. If omitted, defaults to the documentation
string of the R method if any, otherwise None.
To retrieve a property's documentation, use this form:
C.p.__doc__
class C(object):
def __init__(self):
self.__x=None
def getx(self):
print "+++ getx()"
return self.__x
def setx(self, v):
>>> c=C()
>>> print c.x
+++ getx()
None
>>> print C.x.__doc__
Me property 'x'.
>>> c.x=15
+++ setx(15)
>>> c.x
+++ getx()
15
>>> del c.x
+++ delx()
>>> c.x
+++ getx()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in getx
AttributeError: 'C' object has no attribute '_C__x'
reload(moduleName)
The moduleName is the actual name of the module, not a string containing its name. For example, if
you have imported a module like this:
import parrot
>>> s='Wensleydale'
>>> print s
setattr(I, A, V)
Example:
The result is a slice that is equivalent to start:limit:step. Use None to get the default value for
any of the three arguments.
Examples:
>>> r = range(9)
>>> r
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> r[::2]
[0, 2, 4, 6, 8]
>>> r[slice(None, None, 2)]
[0, 2, 4, 6, 8]
>>> r[3:7]
[3, 4, 5, 6]
>>> r[slice(3,7)]
[3, 4, 5, 6]
>>> r[1::2]
[1, 3, 5, 7]
@staticmethod
def methodName(...):
method body
An alternative is to place a line like this after the method's definition (at the same indentation level as
its def):
methodName = staticmethod(methodName)
Assignment Section 15.1, “The assignment statement: name = expression” (p. 69).
assert Section 15.2, “The assert statement: Verify preconditions” (p. 72).
break Section 16.2, “The break statement: Exit a for or while loop” (p. 78).
continue Section 16.3, “The continue statement: Jump to the next cycle of a for or while” (p. 78).
del Section 15.3, “The del statement: Delete a name or part of a value” (p. 73).
elif Section 16.5, “The if statement: Conditional execution” (p. 80) and Section 16.8, “The
try statement: Anticipate exceptions” (p. 82).
else Section 16.5, “The if statement: Conditional execution” (p. 80).
except Section 16.8, “The try statement: Anticipate exceptions” (p. 82).
exec Section 15.4, “The exec statement: Execute Python source code” (p. 73).
finally Section 16.8, “The try statement: Anticipate exceptions” (p. 82).
for Section 16.4, “The for statement: Iteration over a sequence” (p. 79).
from Section 15.6, “The import statement: Use a module” (p. 75).
global Section 15.5, “The global statement: Declare access to a global name” (p. 73).
if Section 16.5, “The if statement: Conditional execution” (p. 80).
import Section 15.6, “The import statement: Use a module” (p. 75).
pass Section 15.7, “The pass statement: Do nothing” (p. 76).
print Section 15.8, “The print statement: Display output values” (p. 76).
raise Section 16.6, “The raise statement: Cause an exception” (p. 81).
return Section 16.7, “The return statement: Exit a function or method” (p. 82).
try Section 16.8, “The try statement: Anticipate exceptions” (p. 82).
yield Section 16.9, “The yield statement: Generate one result from a generator” (p. 85).
In most cases, there will be one target that is a name. Python will evaluate the expression, reducing
it to a single value, and then bind that name to the that value.
A binding is an association between a name and a value. It is important to note that in Python, unlike
many other languages, names themselves are not associated with a specific type. A name is just a label,
and it can be bound to any value of any type at any time. In this example, name x is bound first to an
int value 5, then to a str value 'Some string'.
If a target name was already bound to a value, the name is unbound from that value before it is rebound
to the new value. For each value in a running program, Python keeps track of how many names are
bound to that value. When the value has no more names bound to it, the value's memory is automatically
recycled. If the value is an instance of a class, its destructor may be called; see Section 19.3.8, “__del__():
Destructor” (p. 106).
There are several other forms of assignment statement.
n0 = n1 = ... = expression
If you supply multiple target names, each target will be assigned the value of the expression.
Example:
>>> i = j = errorCount = 0
>>> i
0
>>> j
0
>>> errorCount
0
This feature, called “unpacking,” generalizes to arbritrarily nested sequences within sequences.
You may group targets inside parentheses (...) or brackets [...] to show the levels of nesting.
Here is an example:
All the assignments are effectively simultaneous. Therefore, you can safely exchange the values of
two variables using a statement like this:
v1, v2 = v2, v1
Examples:
name[i] = expression
If name is a list (or other mutable sequence), the expression i must evaluate to an integer. The element
at position i is replaced by the value of the expression.
>>> L = range(6)
>>> L
[0, 1, 2, 3, 4, 5]
>>> L[2]
2
>>> L[2] = 888
>>> L
[0, 1, 888, 3, 4, 5]
If name is a dictionary (or other mapping), and name does not have a key-value pair whose key
equals index, a new key-value pair is added to name with key i and value expression.
As the last two lines show, if the dictionary already has a key-value pair for key i, the old value of
that pair is replaced by the expression value.
name[start:end] = S
If name is a list or other mutable sequence, you can replace the elements of a slice of that sequence
with the elements from some sequence S. (For an explanation of slicing, see Section 7.1, “Operations
common to all the sequence types” (p. 10).) This may result in addition, deletion, or replacement
of the elements of name. Some examples will give the flavor of this kind of assignment.
>>> L=range(6)
>>> L
[0, 1, 2, 3, 4, 5]
>>> L[2:4]
[2, 3]
>>> L[2:4] = [111, 222, 333, 444, 555]
>>> L
[0, 1, 111, 222, 333, 444, 555, 4, 5]
>>> L[3]
Note
The “=” signs in an assignment is not an operator, as it is in some other languages. You cannot assign
a value to a name inside an expression; an assignment statement must stand alone.
>>> a = 5 + (a=7)
File "<stdin>", line 1
a = 5 + (a=7)
^
SyntaxError: invalid syntax
Python also supports augmented assignment. In this form, you may place certain operators before the “=”.
Here is the general form:
An assignment of this general form has the same semantics as this form:
Examples:
>>> i = 1
>>> i += 3
>>> i
4
>>> i *= 5
>>> i
20
assert e1
assert e1, e2
del i, j
would delete the sixth element of list L and the last two elements of list M.
• One entry in a dictionary. For example, if D is a dictionary,
del D['color']
Expression E0 specifies what to execute, and may be a string containing Python source code, an open
file, or a code object. If E1 is omitted, the code is executed in the local scope. If E1 is given but E2 is not,
E1 is a dictionary used to define the names in the global and local scopes. If E2 is given, E1 is a dictionary
defining the global scope, and E2 is a dictionary defining the local scope.
Some conversational examples may help make this clear. Suppose you define a global variable x; you
can use that name inside a function.
>>> x = 5
>>> def show1():
... print x
...
>>> show1()
5
However, if you assign a value to x inside the function, the name x is now local to the function. It is
said to shadow the global variable with the same name, and any changes to the value associated with
that name inside the function will operate on a local copy, and will not affect the value of the global
variable x.
>>> x = 5
>>> def show2():
... x = 42
... print x
...
>>> show2()
42
>>> x
5
But if you actually do want to change the value of the global variable inside the function, just declare
it global like this:
>>> x = 5
>>> def show3():
... global x
... x = 42
... print x
...
>>> show3()
42
>>> x
42
>>> x = 5
>>> def show4():
... print x, "Before"
... x = 42
... print x, "After"
...
>>> show4()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in show4
UnboundLocalError: local variable 'x' referenced before assignment
The first form imports all the items from the module named moduleName. If you want to import only
specific items, use the second form, and enumerate the names you want from that module.
• The import statement makes an entire module's content available to you as a separate namespace.
To refer to some item named N in a module named M, use the dot notation, M.N.
Here is the general form:
If you want to use some module M in this way, but you want to change the name to some different
name A, use this form:
import M as A
Here are some examples that use the standard math module that is always available in a proper Python
install. This module has functions such as sqrt() (square root), as well as variables such as pi. (Although
π is a constant in the mathematical sense, the name pi is a variable in the Python sense.)
If you wanted only the sqrt function and the variable pi, this statement would do the job:
Suppose your program already used the name math for something else, but you still want to use functions
from the math module. You can import it under a different name like this:
while arr():
pass
Each thing must be a string, or a value that can be converted into a string by the str() function (see
Section 13.35, “str(): Convert to str type” (p. 56)). These strings are written to the standard output
stream, with one space between each value. A print statement by itself prints an empty line.
Normally, a newline is printed after the last value. However, you can suppress this behavior by appending
a comma to the end of the list. For example, this statement:
would print the string followed by one space and leave the cursor at the end of that line.
if i < 0:
print "i is negative"
else:
print "i is nonnegative"
if i < 10:
print "i has one digit"
else:
print "i has multiple digits"
If you prefer a more horizontal style, you can always place statements after the colon (:) of a compound
statement, and you can place multiple statements on a line by separating them with semicolons (;).
Example:
You can't mix the block style with the horizontal style: the consequence of an if or else must either
be on the same line or in a block, never both.
break
Here's an example.
Normally this loop would be executed six times, once for each value in the list, but the break statement
gets executed when i is set to an even value.
16.3. The continue statement: Jump to the next cycle of a for or while
Use a continue statement inside a for or while loop when you want to jump directly back to the
top of the loop and go around again.
• If used inside a while loop, the loop's condition expression is evaluated again. If the condition is
False, the loop is terminated; if the condition is True, the loop is executed again.
• Inside a for loop, a continue statement goes back to the top of the loop. If there are any values re-
maining in the sequence of values that controls the loop, the loop variable is set to the next value in
sequence, and the loop body is entered.
If the continue is executed during the last pass through the loop, control goes to the statement after
the end of the loop.
Examples:
>>> i = 0
>>> while i < 10:
... print i,
... i += 1
... if (i%3) != 0:
... continue
... print "num",
...
0 1 2 num 3 4 5 num 6 7 8 num 9
>>> for i in range(10):
... print i,
... if (i%4) != 0:
... continue
... print "whee",
...
0 whee 1 2 3 4 whee 5 6 7 8 whee 9
for V in S:
B
The block is executed once for each value in S. During each execution of the block, V is set to the corres-
ponding value of S in turn. Example:
In general, you can use any number of induction variables. In this case, the members of the controlling
sequence must themselves be sequences, which are unpacked into the induction variables in the same
way as sequence unpacking as described in Section 15.1, “The assignment statement: name = expres-
sion” (p. 69). Here is an example.
For those of you who like to break things, be advised that you can change the induction variable inside
the loop, but during the next pass through the loop, it will be set to the next element of the controlling
sequence normally. Modifying the control sequence itself won't change anything; Python makes a copy
of the control sequence before starting the loop.
if E0:
B0
elif E1:
B1
elif ...:
...
else:
Bf
An if construct may have zero or more elif clauses. The else clause is also optional.
Examples:
raise
raise E1
raise E1, E2
The first form is equivalent to “raise None,None” and the second form is equivalent to “raise E1,
None”. Each form raises an exception of a given type and with a given value. The type and value depend
on how many expressions you provide:
raise E(message)
where E is some class derived from the built-in Exception class: you can use one of the built-in excep-
tions, or you can create your own exception classes.
>>> try:
... raise ValueError('The day is too frabjous.')
... except ValueError, detail:
... pass
...
>>> type(detail)
<type 'exceptions.ValueError'>
>>> detail.message
'The day is too frabjous.'
To create your own exceptions, write a class that inherits from Exception and passes its argument to
the parent constructor, as in this example.
return expression
return
In the first form, execution resumes at the point where the function or method was called, and the value
of the expression is substituted into the calling statement.
The second form is the equivalent of “return None”. (See Section 11, “None: The special placeholder
value” (p. 43).)
try:
B0
except E1[, v1]:
B1
except E2[, v2]:
B2
except ...:
...
else:
Be
finally:
Bf
The else: and finally: blocks are optional. There must be at least one except block, but there may
be any number.
Here is a simplified description of the execution of a try block in general:
1. If B0 executes without raising any exceptions, the else block Be is executed, then the finally
block Bf.
2. If the execution of block B0 raises some exception with type E0, that type is compared to all the
exception classes E1, E2, ... named in the various except clauses.
The criterion for matching is that E0 must be the same class as, or some subclass of, one of the class
names Ei mentioned in an except clause. If there are multiple matches, the first except clause
block Biis executed. In this case, we say that the exception has been caught (or handled).
When an except block matches and is entered, the corresponding variable vi is set to the value
of the exception.
3. If there is a finally clause, it is executed, whether the exception was caught or not. If the exception
was not caught, it is re-raised after the end of the finally clause.
Examples:
>>> try:
... raise ValueError, "Your arm's off."
... except IOError, detail:
... print "I/O error caught:", detail
... except ValueError, detail:
... print "Value error caught:", detail
... except SyntaxError, detail:
... print "Syntax error caught:", detail
... else:
... print "This is the else clause"
... finally:
... print "This is the finally clause"
...
Value error caught: Your arm's off.
This is the finally clause
>>> try:
... raise ValueError, "Uncaught!"
For those of you who are interested in the gory details, the fun begins when a second or even a third
exception is raised inside an except, else, or finally clause. The results are well-defined, and here
is a pseudocode description of the edge cases. In this procedure, we'll use two internal variables named
pending and detail.
1. Set pending to None.
2. Attempt to execute block B0. If this block raises an exception E0 with detail d0, set pending to E0
and set detail to d0.
3. If pending is None, go to Step 8 (p. 84).
4. Find the first block except Ei, vi: such that issubclass(E0, Ei ).
If there is no such match, go to Step 10 (p. 84).
5. Set vi to detail.
6. Attempt to execute block Bi.
If this block raises some new exception En with detail dn, set pending to En and set detail to dn.
However, if block Bi executes without exception, set pending to None. In this case, the original
exception is said to have been caught or handled.
7. Go to Step 10 (p. 84).
8. If there is no else: clause, go to Step 10 (p. 84).
9. Attempt to execute the else: block Be.
If this block raises some new exception En with detail dn, set pending to En and set detail to dn.
10. If there is no finally: clause, proceed to Step 12 (p. 85).
11. Attempt to execute the finally: block Ef.
If pending is None, fall through to the statement following the try: block.
yield expression
Unlike ordinary functions or methods that use the return statement to return a single value, a gener-
ator is a mechanism that produces a sequence of zero or more values. Each execution of a yield statement
produces an additional value. To signal the caller that there are no more values, use this raise statement:
raise StopIteration
As an example, here is a function that generates the sequence 0, 1, 2, ..., n-1, n, n-1, n-2, ..., 2, 1, 0.
def n(p0[=e0][,p1[=e1]]...[,*pv][,**pd]):
B
The name n of the function is followed by a pair of parentheses containing descriptions of the arguments
to the function. The block B is called the body of the function, and is executed when the function is called.
A function may have no arguments at all. If there are arguments to be passed to the function when it is
called, they must be declared in this order:
• A positional argument is a name that is not followed by an equal sign (=) and default value.
• A keyword argument is followed by an equal sign and an expression that gives its default value.
name=expression
• All positional arguments in the function call (if any) must precede all keyword arguments (if any).
• You must supply at least as many positional arguments as the function expects.
• If you supply more positional arguments than the function expects, the extra arguments are matched
against keyword arguments in the order of their declaration in the def. Any additional keyword ar-
guments are set to their default values.
• If you declare a parameter of the form “*name”, the caller can provide any number of additional
keyword arguments, and the name will be bound to a tuple containing those additional arguments.
• Similarly, you may declare a final parameter of the form “**name”. If the caller provides any keyword
arguments whose names do not match declared keyword arguments, that name will be bound to a
dictionary containing the additional keyword arguments as key-value pairs.
>>> x = 'lobster'
>>> y = 'Thermidor'
>>> def f(x):
... y = 'crevettes'
... print x, y
...
>>> f('spam')
spam crevettes
>>> print x, y
lobster Thermidor
iter(S)
• The result of this function is an “iterator object” that can be used in a for statement.
• An iterator must have a .next() method that you can call to get the next element in the sequence.
This method takes no arguments. It returns the next element in the sequence, if any. When there are
no more elements, it raises a StopIteration exception.
yield e
raise StopIteration
For an example of a generator, see Section 16.9, “The yield statement: Generate one result from a
generator” (p. 85).
If you are writing a container class (that is, a class whose instances are containers for a set of values),
and you want to define an iterator (see Section 19.3.14, “__iter__(): Create an iterator” (p. 107)), that
method can be a generator. Here is a small example. The constructor for class Bunch takes a sequence
of values and stores them in instance attribute .__stuffList. The iterator method .__iter__()
generates the elements of the sequence in order, except it wraps each of them in parentheses:
>>> x = 59 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
The above example showed that the offending statement was read from the standard input stream
(<stdin>).
When looking at a traceback, always look at the last line first. It tells you the general type of exception
(in the example, a ZeroDivisionError), followed by additional details (“integer division or modulo
by zero”).
If an exception occurs inside one or more function calls, the traceback will give a complete list of the
functions involved, from outermost to innermost. Again, the last line shows the exception type and
details.
In the example above, function f() calls function g(), which in turn calls function h(). Function h()
raises a ValueError exception, but there is no try: block around it. Python looks to see if there is a
ValueError handler in g(), but there is not. Finally a handler for ValueError is found inside function
f(), so control resumes inside that handler. Note that no stack traceback is displayed, because the
ValueError exception was handled successfully.
>>> try:
... x = 1 / 0
... except Exception, detail:
... print "Fail:", detail.message
...
Fail: integer division or modulo by zero
>>> try:
... x = noSuchVariable
... except Exception, detail:
... print "Fail:", detail.message
...
Fail: name 'noSuchVariable' is not defined
Warning
A catch-all handler like this can mask any number of errors. Do not use such a handler unless your
program must absolutely stay running.
• StopIteration: This is the exception that a generator must raise in order to signal that no more
generated values are available. See Section 17.3, “Generators: Functions that can produce a se-
quence of values” (p. 89).
• StandardError*: This is the base class for all built-in exceptions that are considered errors.
• ArithmeticError*: This is the base class for errors involving arithmetic computations.
• FloatingPointError: This is raised for arithmetic errors involving the float type.
• OverflowError: This is raised when the result of an operation cannot be represented.
• ZeroDivisionError: An attempt to divide by zero.
• AssertionError: An assert statement has failed. See Section 15.2, “The assert statement:
Verify preconditions” (p. 72).
• AttributeError: Failure to access an attribute.
• EnvironmentError*: Errors caused by functions outside of Python, such as the operating
system or peripheral devices.
To declare a class that does not inherit from any parent classes:
class C:
attribute definitions
...
The attribute definitions may include any number of def blocks that declare methods of the
class, and any number of class variable declarations.
Functionally, a class is really just a namespace. This namespace is just a place to store the pieces of the
class mechanisms: its methods and class variables.
• When Python reads a “class” declaration, it creates a new, empty namespace.
• When Python reads a “def” within a class, the name of that method is added to the class's namespace.
12
http://www.nmt.edu/tcc/help/pubs/lang/pytut/obj-intro.html
13
http://www.nmt.edu/tcc/help/pubs/lang/pytut/
1 When Python reads this line, it adds the name Taunter to the current local namespace, bound to
a new, empty namespace of type class.
2 Because this assignment takes place inside class Taunter but not inside a def, name tauntCount
becomes a class variable, bound to an int value of zero.
3 The next two lines define a method named taunt() within the class.
4 After we've finished entering the class definition, we use dir(Taunter) to see what names are
in the class's namespace. Variables __doc__ and __module__ are added automatically. Because
there was no documentation string in the class, __doc__ is bound to None. The __module__
variable has the value '__main__' because the class was entered in conversational mode.
5 To retrieve the value of a class variable V in class C, use the syntax “C.V”.
6 Name taunt in the class namespace is bound to an object of type “unbound method.” An unbound
method is a method (function) that is inside a class, but it is not associated with an instance of the
class.
An instance of a class is also a namespace. When the instance is created, all the names from the class's
namespace are copied into the instance namespace. From that point on, any changes made to the instance's
namespace do not affect the class namespace:
1 This class does not have a constructor (__init__) method, so when an instance is created, the
instance is a namespace with the same names as the class, and the same values.
2 This line adds a new name where to the instance's namespace. It is bound to the string value
'crenelations'.
3 Note that the instance namespace now contains the name where, but the class's namespace is un-
changed.
4 To retrieve an attribute A of an instance I, use the syntax “I.A”. Initially, the instance variable has
the same value as the class variable of the same name.
5 Here, we add one to the instance variable tauntCount. The instance variable has the new value,
but the class variable tauntCount is unchanged.
6 Within the instance namespace, name taunt is now a bound method: it is associated with the instance
frenchy.
The next two lines show two equivalent methods of calling the taunt method.
7 Most method calls are bound method calls. To call a bound method B of an instance I, use the syntax
“I.B(...)”.
When a method B is bound to an instance I, the instance namespace I becomes the “self” argument
passed in to the method.
8 This line has the same effect as the previous line, but it is an unbound method call.
The expression “Taunter.taunt” retrieves the unbound method from the class definition. When
you call an unbound method, you must supply the “self” argument explicitly as the first argument.
Unbound method calls are not terribly common, but you will need to know about them when you
write the constructor for a derived class: you must call the parent class constructor as an unbound
call. Generally, if class D has parent class C, the derived class might look something like this:
class D(C):
def __init__(self, ...):
C.__init__(self, ...)
...
Namespaces are very much like dictionaries. Where a dictionary has unique keys, a namespace has
unique names. As a matter of fact, classes and instances have a special built-in attribute called
“__dict__” which, for most purposes, is the namespace as a dictionary. Continuing the examples
above:
>>> Taunter.__dict__
{'taunt': <function taunt at 0xb7ed002c>, '__module__': '__main__', 'tau
ntCount': 0, '__doc__': None}
>>> newFrenchy=Taunter()
The class's dictionary has the four names we expect: the built-ins __module__ and __doc__, the class
variable tauntCount, and the method taunt.
But notice that the __dict__ attribute of the newly created instance newFrenchy does not have the
four names copied from the class. In fact, it is empty. And the __dict__ of instance frenchy contains
only the names that have changed since its instantation.
What actually happens when you refer to an attribute is that Python looks first in the instance's
__dict__; if the name is not found there, it looks in the __dict__ of the class. For derived classes,
Python will also search the __dict__ attributes of all the ancestor classes.
So, in our example, a reference to frenchy.tauntCount would find the value of 1 in the instance. A
reference to newFrenchy.tauntCount would fail to find that name in newFrench.__dict__, but
would succeed in finding the class variable value 0 in Taunter.__dict__['tauntCount'].
Let's now look at the life cycles of classes in more detail. Due to improvements made in the language
since it was first introduced, Python has two kinds of classes, old-style and new-style. We encourage
you to use new-style classes; old-style classes will no longer be supported in the next major release,
Python 3000.
• All new-style classes must declare at least one parent class that is either the top-level class object
or some other class that derives ultimately from object. Such a class is said to be derived from, or
inherits from, the object class.
To declare a new-style class C that inherits from object:
class C(object):
...class methods and variables...
• An old-style class is one that doesn't declare a parent class at all, or a class that inherits from an existing
old-style class. The life cycle of an old-style class is described in Section 19.1, “Old-style classes” (p. 96).
In most respects, the two classes perform identically.
• We'll start by explaining old-style classes in Section 19.1, “Old-style classes” (p. 96).
• To benefit from the many functional improvements of new-style classes, and especially if you expect
to migrate your code to the major changes of Python 3.0, see Section 19.2, “Life cycle of a new-style
class” (p. 99).
class C:
...class methods and variables...
To create a class that inherits from one or more parent classes P1, P2, …:
As Python reads the definition of your class, it first creates a new, empty namespace called the class
namespace. You can access the class namespace directly as an attribute named __dict__, a dictionary
whose keys are the names in that namespace.
As Python reads each method or class variable in your class declaration, it adds the name of that
method or variable to the class namespace.
The instance creation (also called instantiation) is handled by the __init__() or constructor method.
1. First Python creates the instance with an empty .__dict__ attribute that will contain the instance's
values.
2. Python then calls the constructor. The argument list for this call always has the special first argument
self (the instance), followed by whatever arguments were used in the initial call. The constructor
call is equivalent to this:
3. The constructor method then executes. Typically the constructor will set up new instance attributes
by assignments of this form:
self.name = expression
When the constructor finishes executing, the instance is returned to the constructor's caller.
When you call a method M of an instance I in an expression of the form “I.M(...)”, this is considered
just another attribute “get” operation: the get operation I.M retrieves the method, and then that
method is called using the arguments inside the “(...)”.
• To set an attribute means to give it a value. If there is an existing attribute with the same name, its old
value is discarded, and the attribute name is bound to the new value. The new value is stored in the
instance's .__dict__.
>>> c.thingy
42
>>> c.thingy = 58
>>> c.thingy
58
>>> c.__dict__['thingy']
58
• You can delete an attribute from an instance using a del statement (see Section 15.3, “The del statement:
Delete a name or part of a value” (p. 73)).
>>> c.thingy
58
>>> del c.thingy
>>> c.thingy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: C instance has no attribute 'thingy'
In addition to ordinary attributes and methods, your class can accept references to names that do not
exist in the instance or class namespace. You can define special methods that will be called when some
statement tries to get, set, or delete an attribute that isn't found in the instance's .__dict__. See Sec-
tion 19.3.11, “__getattr__(): Handle a reference to an unknown attribute” (p. 106), Section 19.3.17,
“__setattr__(): Intercept all attribute changes” (p. 108), and Section 19.3.9, “__delattr__(): Delete
an attribute” (p. 106).
If all else fails—if an attribute is not found in the instance's namespace and the class does not provide
a special method that handles the attribute reference—Python will raise an AttributeError exception.
>>> class C:
... def __init__(self, x): self.x = x
... def show(self, y): print "*** (%s,%s) ***" % (self.x, y)
...
>>> c=C(42)
>>> c.show(58)
*** (42,58) ***
>>> C.show(c,58)
*** (42,58) ***
def __del__(self):
...cleanup statements...
14
http://docs.python.org/ref/datamodel.html
C(*p, **k)
That is, it can have any number of positional arguments and any number of keyword arguments.
The equivalent call to the .__new__() method will look like this:
object.__new__(cls)
However, if the .__new__() method does not return an instance of class cls, the constructor method
.__init__() will not be called. This allows the class more control over how new instances are created
and initialized. You can return an instance of an entirely different class if you like.
100 Python 2.5 quick reference New Mexico Tech Computer Center
5. If all searches in the preceding step failed and the instance has a .__getattr__() special method,
call that method. See Section 19.3.11, “__getattr__(): Handle a reference to an unknown attrib-
ute” (p. 106); please note the differences from Section 19.3.12, “__getattribute__(): Intercept
all attribute references” (p. 106).
6. If all the above steps fail to produce a value, raise AttributeError.
Here's a small example. Suppose you want instances of class Point to contain nothing more than two
attributes named .x and .y:
New Mexico Tech Computer Center Python 2.5 quick reference 101
When you declare a __slots__ attribute in a new-style class, instances will not have a .__dict__
attribute.
102 Python 2.5 quick reference New Mexico Tech Computer Center
The self argument is the left-hand operand and the other argument is the operand on the right hand
of the operator.
Each method must return a numeric value:
• A negative number indicates that self precedes other.
• Zero indicates that self and other are considered equal.
• A positive number indicates that other precedes self.
The self argument is the left-hand operand, and the other argument is the right-hand operand. Your
method will return the result of the operation.
For each operator, you may supply up to three methods:
• The method in the first column performs the normal operation.
• The method in the second column is used when the left-hand operand does not support the given
operation and the operands have different types. In these methods, self is the right-hand operand
and other is the left-hand operand.
• The third column implements the “augmented assignment” operators such as “+=”. For example, for
method __iadd__(self, other), the method must perform the equivalent of “self += other”.
New Mexico Tech Computer Center Python 2.5 quick reference 103
Operator Normal Reversed Augmented
- __sub__ __rsub__ __isub__
^ __xor__ __rxor__ __ixor__
def __method__(self):
...
Operator Method
~ __invert__
- __neg__
+ __pos__
In this method, the value of the first argument will be passed to self and the second argument to
other.
Function Method
abs __abs__
complex __complex__
divmod __divmod__
hex __hex__
int __int__
len __len__
long __long__
mod __mod__
oct __oct__
str __str__
unicode __unicode__
104 Python 2.5 quick reference New Mexico Tech Computer Center
19.3.5. __call__(): What to do when someone calls an instance
If a class has a .__call__() method, its instances can be called as if they were functions.
Any arguments passed in that function call become arguments to the .__call__() method. Example:
The convention for return values is the same one described in Section 13.6, “cmp(): Compare two val-
ues” (p. 46): negative if self precedes other, positive if other precedes self, zero if they are con-
sidered equal.
New Mexico Tech Computer Center Python 2.5 quick reference 105
19.3.8. __del__(): Destructor
If a class has a .__del__() method, that method is called when an instance is deleted. For details, see
Section 19.1.5, “Instance deletion: the destructor, .__del__()” (p. 99).
del s[i]
Such a statement can be used either on objects that act like sequences, where i specifies the position of
the element to be deleted, or mapping objects (that is, dictionary-like objects), where i is the key of the
key-value pair to be deleted.
The calling sequence is:
The argument is the name of the desired attribute. The method must either return the attribute's value
or raise an AttributeError exception.
Compare Section 19.3.12, “__getattribute__(): Intercept all attribute references” (p. 106), which is
called even if the instance namespace does have an attribute with the desired name.
106 Python 2.5 quick reference New Mexico Tech Computer Center
19.3.13. __getitem__(): Get one item from a sequence or mapping
If a class defines it, this special method is called whenever a value is retrieved from a sequence or
mapping (dictionary-like object) using the syntax “v[i]”, where v is the sequence or mapping and i
is a position in a sequence, or a key in a mapping.
Here is the calling sequence:
The method either returns the corresponding item or raises an appropriate exception: IndexError for
sequences or KeyError for mappings.
def __iter__(self):
...
The return value must be an iterator. An iterator is any object that has a .next() method that returns
the next value in sequence, or raises StopIteration when the sequence is exhausted. For more in-
formation, see Section 17.2, “Iterators: Values that can produce a sequence of values” (p. 88).
def __nonzero__(self):
...
def __repr__(self):
...
New Mexico Tech Computer Center Python 2.5 quick reference 107
19.3.17. __setattr__(): Intercept all attribute changes
If a class defines it, this method is called whenever a new value is stored into an attribute. Calling se-
quence:
The method sets the attribute given by the name argument to the value argument, or raises Attrib-
uteError if that operation is not permitted.
V[i] = expr
For sequence-type objects, the i argument specifies the position in the sequence to be modified. For
mappings, the i argument is the key under which the value is to be stored.
108 Python 2.5 quick reference New Mexico Tech Computer Center
@classmethod
def methodName(cls, ...):
...
When this method is called, the first argument (cls) will be the class containing methodName.
There are two ways to call a class method: using its class C, or an instance i. These two general forms
are:
C.methodName(...)
i.methodName(...)
In the first case, the class C is passed as the cls argument of the method. In the second case, the class
of instance i is passed as the cls argument.
New Mexico Tech Computer Center Python 2.5 quick reference 109
>>> import pdb
>>> import yourModule
>>> yourModule.test()
[crash traceback appears here]
>>> pdb.pm()
(pdb)
(pdb)
At this prompt, you can type any of the pdb commands discussed below. You can abbreviate any
command by omitting the characters in square brackets. For example, the where command can be ab-
breviated as simply w.
expr
Evaluate an expression expr and print its value.
!stmt
Execute a Python statement stmt. The “!” may be omitted if the statement does not resemble a
pdb command.
(empty line)
If you press Enter at the (pdb) prompt, the previous command is repeated. The list command
is an exception: an empty line entered after a list command shows you the next 11 lines after the
ones previously listed.
a[rgs]
Display the argument names and values to the currently executing function.
b[reak] [[filename:]lineno[,condition]] b[reak] [function[,condition]]
The break command sets a breakpoint at some location in your program. If execution reaches a
breakpoint, execution will be suspended and you will get back to the (pdb) prompt.
110 Python 2.5 quick reference New Mexico Tech Computer Center
The first form sets a breakpoint at a specific line in a source file. Specify the line number within
your source file as lineno; add the filename: if you are working with multiple source files, or
if your source file hasn't been loaded yet.
The second form sets a breakpoint on the first executable statement of the given function.
You can also specify a conditional breakpoint, that is, one that interrupts execution only if a given
condition evaluates as true. For example, the command break 92,i>5 would break at line 92
only when i is greater than 5.
When you set a breakpoint, pdb prints a “breakpoint number.” You will need to know this number
to clear the breakpoint.
c[ont[inue]]
Resume execution until the next breakpoint (if any).
cl[ear] [lineno]
If used without an argument, clears all breakpoints. To clear one breakpoint, give its breakpoint
number (see break above).
h[elp] [cmd]
Without an argument, prints a list of valid commands. Use the cmd argument to get help on command
cmd.
l[ist] [begin[,end]]
Displays your Python source code. With no arguments, it shows 11 lines centered around the current
point of execution. The line about to be executed is marked with an arrow (->), and the letter B
appears at the beginning of lines with breakpoints set.
To look at a given range of source lines, use the begin argument to list 11 lines around that line
number, or provide the ending line number as an end argument. For example, the command list
50,65 would list lines 50-65.
n[ext]
Like step, but does not stop upon entry to a called function.
q[uit]
Exit pdb.
r[eturn]
Resume execution until the current function returns.
s[tep]
Single step: execute the current line. If any functions are called in the current line, pdb will break
upon entering the function.
tbreak
Same options and behavior as break, but the breakpoint is temporary, that is, it is removed after
the first time it is hit.
w[here]
Shows your current location in the program as a stack traceback, with an arrow (->) pointing to
the current stack frame.
New Mexico Tech Computer Center Python 2.5 quick reference 111
21. Commonly used modules
The sections below discuss only a tiny fraction of the official and unofficial module library of Python.
For a full set, consult the Python Library Reference15.
If you want to use any of these modules, you must import them. See Section 15.6, “The import statement:
Use a module” (p. 75).
15
http://docs.python.org/lib/
16
http://docs.python.org/lib/module-cmath.html
112 Python 2.5 quick reference New Mexico Tech Computer Center
sqrt(x) Square root of x.
tan(x) Tangent of x.
tanh(x) Hyperbolic tangent of x.
octdigits
The octal digits: "01234567".
printable
A string containing all the printable characters.
punctuation
All printable characters that are not letters or digits, to wit:
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
uppercase
All the uppercase characters: "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
whitespace
A string containing all the characters considered to be white space, namely:
"\t\n\x0b\x0c\r "
In order, they are: tab, newline, vertical tab, form feed, carriage return, and space.
New Mexico Tech Computer Center Python 2.5 quick reference 113
21.3. random: Random number generation
Any one who considers arithmetical methods of producing random digits is, of course, in a state of sin.
For, as has been pointed out several times, there is no such thing as a random number—there are only
methods to produce random numbers, and a strict arithmetic procedure of course is not such a method.
-- John von Neumann17
This module provides for the generation of pseudorandom numbers.
choice(L)
Returns a randomly selected element from a sequence L.
normalrand(m,s)
Generate a normally distributed pseudorandom number with mean m and standard deviation s.
randint(x,y)
Returns a random integer in the closed interval [x,y]; that is, any result r will satisfy x <= r <=
y.
random()
Returns a random float in the half-open interval [0.0, 1.0); that is, for any result r, 0.0 <= r <
1.0.
randrange([start,]stop[,step])
Return a random element from the sequence range(start,stop,step) .
17
http://en.wikiquote.org/wiki/John_von_Neumann
114 Python 2.5 quick reference New Mexico Tech Computer Center
...
12 2 7 2 17 17 7 7 12 17 17 2 7 17 12 7 7 12 17 17 7 12 7 7 7 7 7 7
shuffle(L)
Randomly permute the elements of a sequence L.
Here's an example. First we build a (small) deck of cards, using a list comprehension to build a list
of all possible combinations of three ranks (ace, king, queen) and four suits (spades, hearts, diamonds,
and clubs). Then we shuffle the deck twice and inspect the results.
uniform(x,y)
Returns a random float in the half-open interval [x,y); that is, each result r will satisfy x <= r <
y.
An assortment of other pseudorandom distributions is available. See the Python Library Reference18 for
details.
18
http://docs.python.org/lib/module-random.html
19
http://docs.python.org/lib/module-datetime
New Mexico Tech Computer Center Python 2.5 quick reference 115
T[4] Minute, in [0,59].
116 Python 2.5 quick reference New Mexico Tech Computer Center
%B Full month name, e.g., 'July'.
%d Day of the month, two digits with left zero fill; e.g. '03'.
%H Hour on the 24-hour clock, two digits with zero fill.
%I Hour on the 12-hour clock, two digits with zero fill.
%j Day of the year as a decimal number, three digits with zero fill, e.g. '366'.
%m Decimal month, two digits with zero fill.
%M Minute, two digits with zero fill.
%p Either 'AM' or 'PM'. Midnight is considered AM and noon PM.
%S Second, two digits with zero fill.
%w Numeric weekday: 0 for Sunday, 6 for Saturday.
20
%y Two-digit year. Not recommended!
%Y Four-digit year.
%Z If there is a time zone, a string representing that zone; e.g., 'PST'.
%% Outputs the character %.
20
http://en.wikipedia.org/wiki/Y2k
21
http://docs.python.org/lib/module-re.html
New Mexico Tech Computer Center Python 2.5 quick reference 117
r+? Non-greedy form of r+.
r?? Non-greedy form of r?.
r{m,n} Matches from m to n repetitions of r. For example, r'x{3,5}' matches between three
and five copies of letter 'x'; r'(bl){4}' matches the string 'blblblbl'.
r{m,n}? Non-greedy version of the previous form.
[...] Matches one character from a set of characters. You can put all the allowable characters
inside the brackets, or use a-b to mean all characters from a to b inclusive. For example,
regular expression r'[abc]' will match either 'a', 'b', or 'c'. Pattern r'[0-9a-zA-
Z]' will match any single letter or digit.
[^...] Matches any character not in the given set.
rs Matches expression r followed by expression s.
r|s Matches either r or s.
(r) Matches r and forms it into a group that can be retrieved separately after a match; see
MatchObject, below. Groups are numbered starting from 1.
(?:r) Matches r but does not form a group for later retrieval.
(?P<n>r) Matches r and forms it into a named group, with name n, for later retrieval.
\n Matches the same text as a group that matched earlier, where n is the number of that group. For
example, r'([a-zA-Z]+):\1' matches the string "foo:foo".
\A Matches only at the start of the string.
\b Matches the empty string but only at the start or end of a word (where a word is set off by
whitespace or a non-alphanumeric character). For example, r'foo\b' would match "foo" but
not "foot".
\B Matches the empty string when not at the start or end of a word.
\d Matches any digit.
\D Matches any non-digit.
\s Matches any whitespace character.
\S Matches any non-whitespace character.
\w Matches any alphanumeric character.
\W Matches any non-alphanumeric character.
\Z Matches only at the end of the string.
\\ Matches a backslash (\) character.
re.match(r,s)
However, if you will be matching the same regular expression many times, the performance will be
better if you compile the regular expression like this:
118 Python 2.5 quick reference New Mexico Tech Computer Center
re.compile(r)
The re.compile() function returns a compiled regular expression object. You can then check a string
s for matching by using the .match(s) method on that object.
Here are the functions in module re:
compile(r[,f])
Compile regular expression r. This function returns a compiled regular expression object; see Sec-
tion 21.5.3, “Compiled regular expression objects” (p. 119). To get case-insensitive matching, use
re.I as the f argument. There are other flags that may be passed to the f argument; see the Python
Library Reference22.
match(r,s[,f])
If r matches the start of string s, return a MatchObject (see below), otherwise return None.
search(r,s[,f])
Like the match() method, but matches r anywhere in s, not just at the beginning.
split(r,s[,maxsplit=m])
Splits string s into pieces where pattern r occurs. If r does not contain groups, returns a list of the
parts of s that match r, in order. If r contains groups, returns a list containing all the characters
from s, with parts matching r in separate elements from the non-matching parts. If the m argument
is given, it specifies the maximum number of pieces that will be split, and the leftovers will be re-
turned as an extra string at the end of the list.
sub(r,R,s[,count=c])
Replace the leftmost non-overlapping parts of s that match r using R; returns s if there is no match.
The R argument can be a string or a function that takes one MatchObject argument and returns
the string to be substituted. If the c argument is supplied (defaulting to 0), no more than c replace-
ments are done, where a value of 0 means do them all.
22
http://docs.python.org/lib/module-re.html
New Mexico Tech Computer Center Python 2.5 quick reference 119
21.5.4. Methods on a MatchObject
A MatchObject is the object returned by .match() or other methods. Such an object has these
methods:
.end([n])
Returns the location where a match ended. If no argument is given, returns the index of the first
character past the match. If n is given, returns the index of the first character past where the nth
group matched.
.endpos
The effective pe value passed to .match() or .search().
.group([n])
Retrieves the text that matched. If there are no arguments, returns the entire string that matched.
To retrieve just the text that matched the nth group, pass in an integer n, where the groups are
numbered starting at 1. For example, for a MatchObject m, m.group(2) would return the text
that matched the second group, or None if there were no second group.
If you have named the groups in your regular expression using a construct of the form
(?P<name>...), the n argument can be the name as a string. For example, if you have a group
(?P<year>[\d]{4}) (which matches four digits), you can retrieve that field using
m.group('year').
.groups()
Return a tuple (s1,s2,...) containing all the matched strings, where si is the string that matched
the ith group.
.pos
The effective ps value passed to .match() or .search().
.re
The regular expression object used to produce this MatchObject.
.span([n])
Returns a 2-tuple (m.start(n),m.end(n)).
.start([n])
Returns the location where a match started. If no argument is given, returns the index within the
string where the entire match started. If an argument n is given, returns the index of the start of the
match for the nth group.
.string
The s argument passed to .match() or .search().
120 Python 2.5 quick reference New Mexico Tech Computer Center
exit(n)
Terminate execution with status n.
modules
A dictionary of the modules already loaded.
path
The search path for modules, a list of strings in search order.
Note: You can modify this list. For example, if you want Python to search directory /u/dora/py-
thon/lib for modules to import before searching any other directory, these two lines will do it:
import sys
sys.path.insert(0, "/u/dora/python/lib")
platform
A string identifying the software architecture.
stderr
The standard error stream as a file object.
stdin
The standard input stream as a file object.
stdout
The standard output stream as a file object.
New Mexico Tech Computer Center Python 2.5 quick reference 121
_exit(n)
Exit the current process and return status code n. This method should be used only by the child
process after a fork(); normally you should use sys.exit().
fork()
Fork a child process. In the child process, this function returns 0; in the parent, it returns the child's
process ID.
getcwd()
Returns the current working directory name as a string.
getegid()
Returns the effective group ID.
geteuid()
Returns the effective user ID.
getgid()
Returns the current process's group ID. To decode user IDs, see the grp standard module23.
getpid()
Returns the current process's process ID.
getppid()
Returns the parent process's PID (process ID).
getuid()
Returns the current process's user ID. To decode user IDs, see the pwd standard module24.
kill(p,s)
Send signal s to the process whose process ID is p.
link(s,d)
Create a hard link to s and call the link d.
listdir(p)
Return a list of the names of the files in the directory whose pathname is p. This list will never
contain the special entries '.' and '..' for the current and parent directories. The entries may
not be in any particular order.
lstat(p)
Like stat(), but if p is a link, you will get the status tuple for the link itself, rather than the file it
points at.
mkdir(p[,m])
Create a directory at pathname p. You may optionally specify permissions m; see module stat below
for the interpretation of permission values.
mkfifo(p,m)
Create a named pipe with name p and open mode m. The server side of the pipe will open it for
reading, and the client side for writing. This function does not actually open the fifo, it just creates
the rendezvous point.
nice(i)
Renice (change the priority) of the current process by adding i to its current priority.
23
http://docs.python.org/library/pwd.html
24
http://docs.python.org/library/pwd.html
122 Python 2.5 quick reference New Mexico Tech Computer Center
readlink(p)
If p is the pathname to a soft (symbolic) link, this function returns the pathname to which that link
points.
remove(p)
Removes the file with pathname p, as in the Unix rm command. Raises OSError if it fails.
rename(po, pn)
Rename path po to pn.
rmdir(p)
Remove the directory at path p.
stat(p)
Return a status tuple describing the file or directory at pathname p. See module stat, below, for
the interpretation of a status tuple. If p is a link, you will get the status tuple of the file to which p
is linked.
symlink(s,d)
Create a symbolic link to path s, and call the link d.
system(c)
Execute the command in string c as a sub-shell. Returns the exit status of the process.
times()
Returns a tuple of statistics about the current process's elapsed time. This tuple has the form
(u,s,u',s',r) where u is user time, s is system time, u' and s' are user and system time includ-
ing all child processes, and r is elapsed real time. All values are in seconds as floats.
umask(m)
Sets the “umask” that determines the default permissions for newly created files. Returns the previous
value. Each bit set in the umask corresponds to a permission that is not granted by default.
uname()
Returns a tuple of strings descriping the operating system's version: (s,n,r,v,m) where s is the
name of the operating system, n is the name of the processor (node) where you are running, r is
the operating system's version number, v is the major version, and m describes the type of processor.
utime(p,t)
The t argument must be a tuple (a, m) where a and m are epoch times. For pathname p, set the
last access time to a and the last modification to m.
wait()
Wait for the termination of a child process. Returns a tuple (p,e) where p is the child's process ID
and e is its exit status.
waitpid(p,o)
Like wait(), but it waits for the process whose ID is p. The option value o specifies what to do if
the child is still running. If o is 0, you wait for the child to terminate. Use a value of os.WNOHANG
if you don't want to wait.
WNOHANG
See waitpid() above.
New Mexico Tech Computer Center Python 2.5 quick reference 123
First, there are constants for indexing the components of a “status tuple” such as that returned by
os.stat():
ST_ATIME The epoch time of last access (see the time module for interpretation of times).
ST_CTIME The epoch time of the file's last status change.
ST_DEV The device number.
ST_GID The group ID.
ST_INO The i-node number.
ST_MODE The file's permissions.
ST_MTIME The epoch time of last modification.
ST_NLINK The number of hard links.
ST_SIZE The current size in bytes.
ST_UID The user ID.
The following functions are defined in the stat module for testing a mode value m, where m is the
ST_MODE element of the status tuple. Each function is a predicate:
These constants are defined for use as mask values in testing and assembling permission values such
as those returned by os.stat() in Section 21.7, “os: The operating system interface” (p. 121).
124 Python 2.5 quick reference New Mexico Tech Computer Center
21.9. os.path: File and directory interface
These functions allow you to deal with path names and directory trees. To use a given method in this
module, import the os module and then use os.path.method().
For example, to get the base name of a path p, use os.path.basename(p).
abspath(p)
Return the absolute path name that is equivalent to path p.
basename(p)
Return the base name portion of a path name string p. See split(), below.
commonprefix(L)
For a list L containing pathname strings, return the longest string that is a prefix of each element in
L.
exists(p)
Predicate for testing whether pathname p exists.
expanduser(p)
If p is a pathname starting with a tilde character (~), return the equivalent full pathname; otherwise
return p.
isabs(p)
Predicate for testing whether p is an absolute pathname (e.g., starts with a slash on Unix systems).
isfile(p)
Predicate for testing whether p refers to a regular file, as opposed to a directory, link, or device.
islink(p)
Predicate for testing whether p is a soft (symbolic) link.
ismount(p)
Predicate for testing whether p is a mount point, that is, whether p is on a different device than its
parent directory.
join(p,q)
If q is an absolute path, returns q. Otherwise, if p is empty or ends in a slash, returns p+q, but oth-
erwise it returns p+'/'+q.
normcase(p)
Return pathname p with its case normalized. On Unix systems, this does nothing, but on Macs it
lowercases p.
samefile(p,q)
Predicate for testing whether p and q are the same file (that is, the same inode on the same device).
This method may raise an exception if os.stat() fails for either argument.
split(p)
Return a 2-tuple (H,T) where T is the tail end of the pathname (not containing a slash) and H is
everything up to the tail. If p ends with a slash, returns (p,''). If p contains no slashes, returns
('',p). The returned H string will have its trailing slash removed unless H is the root directory.
splitext(p)
Returns a 2-tuple (R,E) where E is the “extension” part of the pathname and R is the “root” part.
If p contains at least one period, E will contain the last period and everything after that, and R will
be everything up to but not including the last period. If p contains no periods, returns (p,'').
New Mexico Tech Computer Center Python 2.5 quick reference 125
walk(p,V,a)
Walks an entire directory structure starting at pathname p. See below for more information.
The os.path.walk(p,V,a) function does the following for every directory at or below p (including
p if p is a directory), this method calls the “visitor function” V with arguments
V(a,d,N)
a The same a passed to os.path.walk(). You can use a to provide information to the V() function,
or to accumulate information throughout the traversal of the directory structure.
d A string containing the name of the directory being visited.
N A list of all the names within directory d. You can remove elements from this list in place if there
are some elements of d that you don't want walk() to visit.
126 Python 2.5 quick reference New Mexico Tech Computer Center