Python is an interpreted, general-purpose high-level programming language. I'm parking random notes on Python here. Python was conceived and initially implemented by Guido van Rossum at CWI in the Netherlands as a successor to the ABC programming language.

Set Up

As of 2013-02-04, there are 2 major versions of Python: 2.* and 3.*. Python 3.* is cutting edge and NOT backwards compatible. Most modules are written for 2.* so unless you explicitly need 3.*, get 2.* instead.

Hello world examples:

print "Hello, world!"  # Python 2.*
print("Hello, world!") # Python 3.*

Code on this page assumes Python 2.* unless otherwise noted.

If you're going to use a Windows command prompt, then add python to the path with something like this: set path=%path%;C:\Python27. You can install and use multiple versions of Python, but only one version is the default as set in the path. Then simply type python to get to the interpreter. Type an end-of-file character (Ctrl+D on Unix, Ctrl+Z on Windows) to exit the interpreter with a zero exit status. Or type quit().

The version of python is shown at the start up of a command line interface (CLI). You can also find it by entering import sys then sys.version.

On windows, .py or .pyw files are usually Pythons scripts/programs associated with Python and will execute when double-clicked or run in the CLI with python yourPythonApp.py. Python program files hould start with a letter; Any additional characters should be letters, numbers, dashes (-), or underscores (_). Note that Python doesn't allow dashes in identifiers.

When used from a command line interface, the Python interpreter is said to be in interactive mode. The primary prompt is usually 3 greater-than signs (>>>), while a continuation line has a secondary prompt of usually 3 dots (...).

There are 3 basic CLIs: Python IDLE (aka Python GUI), Python CLI, and an OS CLI. And yet a Python mantra is that there should be one obvious way to do it.

You can run Python code in interactive mode, but generally speaking you have code in *.py file and run that directly or via the CLI.

Lexical Basics

# starts a comment in Python and extends to the end of the physical line.

Python uses logical lines for most statements. Two or more physical lines can be explicitly joined into one logical line with backslashes (\). A joining backslash cannot be followed by a comment on the same physical line. A comment cannot be continued.

year = 1968
month = 10
if 1900 < year < 2100 \
    and 1 <= month <= 12: # Commment OK here but not on prev line
        'hello world'

Expressions in parentheses, square brackets, or curly braces can be implicitly split over physical lines without backslashing. Implicitly joined lines can take comments.

family_names = [
    'George', # Dad
    'Julia'] # Mom            

Python uses indentation for grouping.

// c-like example:
if (x == 6) {
    x = x + 78;
    return x;
}
# Python example:
if x == 6:
    x = x + 78
    return x

Python identifiers include letters (A-Z, a-z), numbers (0-9), and underscore (_). No dashes (-)!

Python operators:

Python delimiters: ( ) [ ] { } @ , : . ` = ;.

Python delimiters that are also operators: += -= *= /= //= %= &= |= ^= >>= <<= **=.

Other characters that have special meaning in Python: ... ' } # \.

Characters that will cause an error in Python if outside of string literals: $ ?.

Python reserved words: and, as, 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, with, yield.

Python built-in functions [2011-09]:

abs(x)
all(iterable)
any(iterable)
basestring()
bin(x)
bool([x])
bytearray([source[, encoding[, errors]]])
callable(object)
chr(i)
classmethod(function)
cmp(x,y)
compile(source, filename, mode[, flags[, dont_inherit]])
complex([real[, imag]])
delattr(object, name)
dict([arg])
dir([object])
divmod(a, b)
enumerate(sequence[, start=0])
eval(expression[, globals[, locals]])
execfile(filename[, globals[, locals]])
file(filename[, mode[, bufsize]])
filter(function, iterable)
float([x])
format(value[, format_spec])
frozenset([iterable])
getattr(object, name[, default])
globals()
hasattr(object, name)
hash(object)
help([object])
hex(x)
id(object)
input([prompt]). BEWARE: Everything entered into input() is evaluated as a Python expression.
int([x[, base]])
isinstance(object, classinfo)
issubclass(class, classinfo)
iter(o[, sentinel])
len(s)
list([iterable])
locals()
long([x[, base]])
map(function, iterable, ...)
max(iterable[, args...][, key])
memoryview(obj)
min(iterable[, args...][, key])
next(iterator[, default])
object()
oct(x)
open(name[, mode[, buffering]])
ord(c)
pow(x, y[, z])
print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout])
property([fget[, fset[, fdel[, doc]]]])
range([start], stop[, step])
raw_input([prompt]). Returns a string.
reduce(function, iterable[, initializer])
reload(module)
repr(object)
reversed(seq)
round(x[, n])
set([iterable])
setattr(object, name, value)
slice([start], stop[, step])
sorted(iterable[, cmp[, key[, reverse]]])
staticmethod(function)
str([object])
sum(iterable[, start])
super(type[, object-or-type])
tuple([iterable])
type(object)
type(name, bases, dict)
unichr(i)
unicode([object[, encoding[, errors]]])
vars([object])
xrange([start], stop[, step])
zip([iterable, ...])
__import__(name[, globals[, locals[, fromlist[, level]]]])

These are considered deprecated:

apply(function, args[, keywords])
buffer(object[, offset[, size]])
coerce(x, y)
intern(string)

Python built-in constants: False, True, None, NotImplemented, Ellipsis, __debug__.

Operator precedence in Python:

Operator Description
lambdaLamda expression
if elseConditional expression
orBoolean OR
andBoolean AND
notBoolean NOT
in, not in, is, is not, <, <=, >, >=, <>, !=, ==Comparisons, membership test (sequences only), identity tests
|Bitwise OR
^Bitwise XOR
&Bitwise AND
<<, >>Shifts
+, -Addition, subtraction
*, /, //, %Multiplication, division, floor division (7 // 3. is 2.0), modulo remainder(7 % 3 is 1)
+x, -x, ~xPositive, negative, bitwise NOT
**Exponentiation. EG: 2**-1 is 0.5.
x[i], x[i:j], x[i:j:k], x(arguments...), x.attributeSubscription, slicing, call, attribute reference
(expressions...), [expressions...], {key:datum...}, `expressions...`Binding or tuple display, list display, dictionary display, string conversion

Any object can be tested for a truth value. The following values are considered false:

Objects and Types

Python abstracts all data as objects. Every object has an identity, a type, and a value.

Here is a list of the standard types built into Python:

  1. None. Signifies the absence of a value, i.e. a null. Its boolean value is false.
  2. NotImplemented. Signifies a non-implented operation. Its boolean value is true.
  3. Ellipsis. Signifies the presence of ... syntax in a slice. Its boolean value is true.
  4. Type. Signifies the type of an object. The built-in function type(object) will return a value like <type 'int'>.
  5. Numbers. Includes:
    • Integral. Integers, long intergers, and boolean.
    • Real. Float.
    • Complex
  6. Sequences. Finite collection of objects indexed by non-negative integers. Includes:
    • Mutable sequences:
      • Strings. EG: 's'.
      • Unicode strings. EG: u's'.
      • Tuples. EG: ('s', u's')).
    • Immutable sequences:
      • Lists. EG: [1, 2].
      • Byte arrays.
  7. Sets. Finite collection of unique objects that are not indexed. Includes:
    • Mutable sets: Sets. Constructor: set([iterable]).
    • Immutable sets: Frozen sets. Constructor: frozenset([iterable]).
  8. Mappings. Finite collection of objects indexed by a set of arbitrary keys. Keys are numbers or strings. Includes:
    • Dictionary Mappings. Mutable. EG: {1: 's', 't': 7}. Access notation: dic[key].
  9. Callable types. Types to which the function call operation can be applied.
    • User-defined functions. Created by a function definition. Has special attributes like func_doc, func_name, func_defaults, func_code, etc.
    • User-defined methods. Combines a class, a class instance, and any callable object (usually a user-defined function).
    • Generator functions
    • Built-in functions
    • Built-in methods
    • Class Types
    • Classic Classes
    • Class instances
    • Files. Represents an open file.
    • Internal types

The built-in len(x) function returns the number of items in x, where x is a sequence, set, or mapping. Sequences, set, and mappings are all iterable types in that they implement the next() method and can use for ... in

Number Types

Python Number types include:

Here are operations available to all number types:

OperationResult
x + y
x - y
x * yproduct of x and y
x / yquotient of x and y. For integers, rounded toward minus infinity
x // yfloored quotient of x and y
x % yremainder of x / y
-x
+x
abs(x)
int(x)
long(x)
float(x)
complex(re, im)a complex number with real part re, imaginary part im. im defaults to zero.
c.conjugate()conjugate of the complex number c. (Identity on real numbers)
divmod(x, y)the pair (x // y, x % y)
pow(x, y) or x ** yx to the power y

Integral numbers can also do this operation: bit_length().

Real numbers can also do these operations: math.trunc(x), round(x[, n]), math.floor(x), math.ceil(x), as_integer_ratio(), is_integer(), hex(), fromhex(s).

Integral

numbers.Integral. Integers, long intergers, and boolean. Examples of Python ingteger literals:

9 # decimal integer, no prefix preferred
09 # decimal integer
-9 # a negative number is the unary operator before a positive number
2147483648L # decimal long integer, upper case preferred
2147483648l # decimal long integer
# Long integers are above 2,147,483,647, the largest 32-bit signed integer
# Long integer variants are available for the other bases but not shown here
0o7 # octal integer, lower case preferred. 
0O7 # octal integer
0XFe # hexadecimal integer
0xFe # hexadecimal integer
0B1 # binary integer
0b1 # binary integer

Real

numbers.Real. Float. Examples of Python floating point literals:

3.14
10.
.001
1e100
3.14E-10
0e+0
-1.7 # a negative number has the unary operator before the number

Methods specific to numbers.Real:

>>> f = 3.5
>>> f.as_integer_ratio()
(7, 2)
>>> f.is_integer()
False
>>> f.hex()
'0x1.c000000000000p+1'
>>> float.fromhex('0x3.a7p10')
3740.0

Complex

numbers.Complex. Examples of Python imaginary number literals:

3j
3.1j
3 + 4J
>>> x = 2 + 3j
>>> x.real
2
>>> x.imag
3

Number Operations

# Assignment:
>>> x = 2
>>> y = 3
>>> x * 3
6
>>> x = y = z = 2 # Simultaneous assignment
>>> x * y * z
8
>>> a, b = 0, 1 # Multiple assignment
>>> b
1

# Misc:
>>> pow(3, 2)
9
>>> 3**2
9
>>> abs(-7)
7

# Integral
>>> bin(2)
'0b10'
>>> 0b10.bit_length()
2
>>> (2).bit_length() # decimal literals err without parentheses
2

# Operations of integers mixed with floating point are converted to floating point:
>>> 2 * 3.2
6.4

# Real/Float
>>> f = 3.5
>>> int(f)
3
>>> long(f)
3L
>>> float(f)
3.5
>>> round(7.555, 2)
7.55
>>> f.as_integer_ratio()
(7, 2)
>>> f.is_integer()
False
>>> f.hex()
'0x1.c000000000000p+1'
>>> float.fromhex('0x3.a7p10')
3740.0

# Imaginary
>>> 1j * 1J # By definition!
(-1+0j)
>>> (3+1j) * 3
(9+3j)
>>> 1j * complex(0, 1)
(-1+0j)
>>> x = 2 + 3j
(2+3j)
>>> x.conjugate()
(2-3j)

The last printed expression is automatically assigned to the variable underscore (_). This is a convenient memory recall. Do not try explicitly assign a value to _: that would make a new fake _ variable that doesn't function the same way as the real _ variable.

>>> 1 / 3.0
0.333333333333
>>> round(_, 2)
0.33

Sequence Types

Sequences. Finite collection of objects indexed by non-negative integers.

Here are some operations available to sequences in ascending priority.

Operation Result
x in s True if an item of s is equal to x, else False
x not in s False if an item of s is equal to x, else True
s + t the concatenation of s and t
s * n, n * s n shallow copies of s concatenated. Nested structures not copied.
s[i] ith item of s, 0-based index. If i is negative, then it is relative to the end of the sequence.
s[i:j] slice of s where <= i and < j. If i or j are negative, then it is relative to the end of the sequence. If i >= j, then returns empty. If i missing, then i is assumed to be 1st. If j is missing, j is assumed to be last.
s[i:j:k] slice of s from i to j with step k. If i or j are negative, then it is relative to the end of the sequence. The indices are i, i+k, i+2*k, i+3*k, ... but never includes k.
len(s) length of s
min(s) smallest item of s
max(s) largest item of s
s.index(i) index of the first occurence of i in s
s.count(i) total number of occurences of i in s

Sequence examples:

>>> s = 'bark'
>>> s[0]
'b'
>>> s[:2] # i defaults to 0
'ba'
>>> s[1:2]
'a'
>>> s[1:] # j defaults to sequence size
'ark'

# Strings are immutable and cannot be written to by index:
>>> s[0] = 'f' # Invalid, would err
>>> s[0] + 'eard' # New string, so OK
'beard'

# Lists are mutable and can be written by index:
>>> a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> a[0] = 0
>>> a
[0, 2, 3]

>>> s[9:] # A too large i, acts as sequence size
''
>>> s[1:9] # A too large j, acts as sequence size
'ark'
>>> s[2:1] # If i >= 2nd, returns empty
''

# Negative indexes start from the right:
>>> s[-1] # Returns last
'k'
>>> s[:-2] # Returns all but last 2
'ba'
>>> len(s) # Returns sequence size
4

Think of the indexes as BETWEEN characters/items:

 +---+---+---+---+
 | b | a | r | k |
 +---+---+---+---+
 0   1   2   3   4
-4  -3  -2  -1   0

Strings

Strings are immutable sequences of characters. Strings can be enclosed in single or double quotes. Escape quotes with a backslash (\). Results are enclosed in double if it contains any singles but no doubles.

>>> 'foo bar'
'foo bar'
>>> "foo bar"
'foo bar'
>>> 'don\'t'
"don't'"
>>> '"No", he said.'
'"No", he said.'
>>> "\"No\", he said."
'"No", he said.'
>>> '"Don\'t," he said.'
'"Don\'t," he said.'

Other escaped sequences are similar to c.

\newline # Ignored
\\ # Backslash
\' # Single quote
\" # Double quote
\a # ASCII bell
\b # ASCII backspace
\f # ASCII formfeed
\n # ASCII linefeed
\name # Character given a Unicode name
\r # ASCII carriage return
\t # ASCII tab
\unnnn # Character given a Unicode nnnn 16-bit hex value
\Unnnnnnnn # Character given a Unicode nnnnnnnn 32-bit hex value
\v # ASCII vertical tab
\onnn # Character with a nnn octal value up to 3 digits
\xnn # Character with a nn hex value exactly 2 digits

Continue lines by backslash escaping the physical end-of-line (EOL):

>>> bar = 'fee\
... fi\n\
...  fo\n\
...   don\'t'
>>> bar
"feefi\n fo\n  don't"
>>> # print displays more cleanly:
>>> print bar
feefi
 fo
  don't

If triple quotes (single or double) are used then escaping the EOLs is not necessary but they will be included in the result:

>>> bar = '''
... one
... two
...  three'''
>>> bar
'\none\ntwo\n three'
>>> print bar

one
two
 three

Raw string literals are prefixed with a letter R or r. The require escaping of physical EOLs, but they include them in the results too.

>>> bar = r'one\
... two\n\
...  three.'
>>> bar
'one\\\ntwo\\n\\\n three'
>>> print bar
one\
two\n\
 three

Strings are concatenated with a plus (+) and repeated with an asterisk (*). String literals (not variables that are strings) can be concatenated with a space.

>>> bar = 'H' + 'i' "Ho"
>>> bar
'HiHo'
>>> bar * 2
'HiHoHiHo'
>>> 'str'.strip() 'ing' # Concatenation errr

The print statement.

# print puts a space between its parameters
>>> print 'The answer is', 7 
The answer is 7

# A trailing comma avoids the newline after the output
>>> a, b = 0, 1
>>> while b < 1000:
...    print b,
...    a, b = b, a + b
...
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

Formatting can be done using either the older format operator (%) or the newer format(*args, **kwargs) method for string or unicode objects. The format placeholder is very similar to the traditional one from ye olde printf: %[parameter][flags][width][.precision][length]type.

>>> t = 'foo bar'
>>> "String: %s, %.3s, %%, {" % (t, t) # precision
'String: foo bar, foo, %, {'
>>> "String: {0}, {0:.3s}, %, {1}".format(t, '{')
'String: foo bar, foo, %, {'

>>> p, n, x = 78, -78, 9
>>> "Decimals: %d, %d, %i, %i" % (p, n, p, n)
'Decimals: 78, -78, 78, -78'
>>> "Decimals: % d, % d, %+d, %+d, %03d" % (p, n, p, n, x)
'Decimals:  78, -78, +78, -78, 009'
>>> "Decimals: %.2d, %03d, %-3d" % (x, x, x) # precision, flags
'Decimals: 09, 009, 9  '
>>> "Octal: {0:o}, {0:#o}".format(p) # flag
'Octal: 116, 0o116'
>>> "Hexadecimal: {0:x}, {0:#x}, {0:X}".format(p)
'Hexadecimal: 4e, 0x4e, 4E'

>>> x, y, z = 12e-34, 5.6, 78e9
>>> "Exponent: {0:.1e}, {1:.3e}, {2:.2E}".format(x, y, z)
'Exponent: 1.2e-33, 5.60e+00, 7.80E+10'
>>> "Float: {0:.1f}, {1:.3f}, {2:.2f}".format(x, y, z)
'Float: 0., 5.60, 78000000000.000'
>>> "Float: {0:.1g}, {1:.3g}, {2:.2G}".format(x, y, z)
'Float: 1e-33, 5.6, 7.8E+10'

>>> "http://fake.com/{0}/{1}.php".format('pots', 42)
'http://fake.com/pots/42.php'
>>> a = ('pots', 42)
>>> "http://fake.com/{0}/{1}.php".format(*a)
'http://fake.com/pots/42.php'
>>> "http://fake.com/%s/%d.php" % a
'http://fake.com/pots/42.php'
>>> "http://fake.com/{cat}/{page}.php".format(cat = 'pots', page = 42)
'http://fake.com/pots/42.php'
>>> b = {'cat': 'pots', 'page': 42}
>>> "http://fake.com/{cat}/{page}.php".format(**b)
'http://fake.com/pots/42.php'
>>> "http://fake.com/%(cat)s/%(page)d.php" % b
'http://fake.com/pots/42.php'

There are many string and unicode methods: capitalize(), center(width[, fillchar]), count(sub[, start[, end]]), decode([encoding[, errors]]), encode([encoding[, errors]]), endswith(suffix[, start[, end]]), expandtabs([tabsize]), find(sub[, start[, end]]), format(*args, **kwargs), index(sub[, start[, end]]), isalnum(), isalpha(), isdigit(), islower(), isspace(), istitle(), isupper(), join(iterable), ljust(width[, fillchar]), lower(), lstrip([chars]), partition(sep), replace(old, new[, count]), rfind(sub[, start[, end]]), rindex(sub[, start[, end]]), rjust(width[, fillchar]), rpartition(sep), rsplit([sep[, maxsplit]]), rstrip([chars]), split([sep[, maxsplit]]), splitlines([keepends]), startswith(prefix[, start[, end]]), strip([chars]), swapcase(), title(), translate(table[, deletechars]), upper(), zfill(width)

chr() and chr() convert between characters and non-negative integers. unichr() and chr() convert between characters and non-negative integers.

Unicode string literals are prefixed with a letter U or u. The default encoding for Python is ASCII, thus Python nomrally takes characters 0-127 and rejects others.

>>> s = u'ä'
>>> s
u'\xe4'
>>> str(s) # Converting to string errs because not ASCII
>>> s.encode('utf-8')
'\xc3\xa4'
>>> unicode('\xc3\xa4', 'utf-8') # try also latin-1, ascii, and utf-16
u'\xe4'

Here are methods specific to unicode objects: isnumeric(), isdecimal().

A tuple can be made without using parenthese (EG: t = 1, 2, 3), but that can cause confusion so you might as well use parentheses. () is an empty tuple. (x,) is a tuple of one item (a singleton); the comma is required.

Sequences can be packed and unpacked. Multiple assignment is an example of this.

>>> t = (3, 4, 5) # Packed
>>> a, b, c = t # Unpacked
>>> a
3

Byte literals are prefixed with a letter B or b.

Xrange is an immutable sequence type, but since it is used for looping via the built-in xrange() function, and the latter is just like the built-in range() function, it is not a major type.

Lists

Lists are mutable sequences of arbitrary Python objects, each of which can be a different type. Its literal form is of comma-separated items enclosed in square brackets ([]). Python is smart enough to ignore a trailing comma in a list if left in by mistake.

>>> foo = ['ack', 'bar', 78, 12,]
>>> foo
['ack', 'bar', 78, 12]

Here are some operations available to mutable sequences:

OperationResult
len(s)returns the length of s
s[i] = xitem i of s is replaced by x
s[i:j] = tslice of s from i to j is replaced by the contents of the iterable t
del s[i:j]same as s[i:j] = []
s[i:j:k] = tthe elements of s[i:j:k] are replaced by those of t
del s[i:j:k]removes the elements of s[i:j:k] from the list
s.append(x)same as s[len(s):len(s)] = [x]
s.extend(x)same as s[len(s):len(s)] = x, where x is any iterable object
s.count(x)return number of i's for which s[i] == x
s.index(x[, i[, j]])return smallest k such that s[k] == x and i <= k < j
s.insert(i, x)same as s[i:i] = [x]
s.pop([i])same as x = s[i]; del s[i]; return x
s.remove(x)same as del s[s.index(x)]
s.reverse()reverses the items of s in place
s.sort([cmp[, key[, reverse]]])sort the items of s in place
"value" in sis True if "value is an element in s
"value" not in sis True if "value is not an element in s

Lists are 0-indexed and can be sliced like strings, but are mutable and writable.

>>> foo = ['ack', 'bar', 78, 12]
>>> foo[1:-1]
['bar', 78]
>>> oof = foo # References same list in memory
>>> foo[-1] = 13
>>> oof[-1] 
13
>>> foo[-1] = 12
>>> bar = foo[:] # copy instead of reference
>>> bar
['ack', 'bar', 78, 12]
>>> foo[:] * 2
['ack', 'bar', 78, 12, 'ack', 'bar', 78, 12]
>>> foo[-1] = foo[-1] + 12 # Change item
>>> foo
['ack', 'bar', 78, 24]
>>> foo[-2:] = [] # Remove items
>>> foo
['ack', 'bar']
>>> foo[1:1] = [13, 19] # Insert items
['ack', 13, 19, 'bar]
>>> foo = [] # Clear list
[]
>>> len(foo) # Returns list size
0

Nested lists are possible.

>>> a = [1, 2, 3]
>>> b = [5, a, 6]
>>> b[1]
[1, 2, 3]
>>> b[1][2]
3
>>> b[1].append(4)
>>> b
[5, [1, 2, 3, 4], 6]

To copy a list that contains lists, you will have to use the deepcopy function.

>>> import copy
>>> a = [[1, 2, 3], [4, 5, 6]]
>>> b = a[:] # shallow copy
>>> c = copy.deepcopy(a)
>>> b[0][1] = 10 # Since b is a reference, it changes a too
>>> c[1][1] = 12 # Since c has a deep copy, it does not affect a
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b
[[1, 10, 3], [4, 5, 6]]
>>> c
[[1, 2, 3], [4, 12, 6]]

Set Types

A Set object is a finite collection of unique/distinct objects that are not indexed. Sets are similar to sequences but sequences are ordered and can be indexed and sliced.

Here are operations available to set and frozenset types: len(s), x in s, x not in s, isdisjoint(other), issubset(other), set <= other, set < other, issuperset(other), set >= other, set > other, union(other, ...), set | other | ..., intersection(other, ...), set & other & ..., difference(other, ...), set - other - ..., symmetric_difference(other), set ^ other, copy()

Here are operations available to set types but not frozenset types: update(other, ...), set |= other | ..., intersection_update(other, ...), set &= other & ..., difference_update(other, ...), set -= other | ..., symmetric_difference_update(other), set ^= other, add(elem), remove(elem), discard(elem), pop(), clear().

>>> numbers = [1, 2, 4, 1, 5, 6, 6]
>>> uniques = set(numbers)
>>> unqiues
set([1, 2, 4, 5, 6])
>>> a = set('abcc')
>>> b = set('cdee')
>>> a
set(['a', 'c', 'b'])
>>> a - b # In a but not in b
set(['a', 'b'])
>>> a | b # In a or b
set(['a', 'c', 'b', 'e', 'd'])
>>> a & b # In a and b
set(['c'])
>>> a ^ b # In a or b, but not both (a xor b)
set(['a', 'b', 'e', 'd'])

Mapping Types

A Mapping object is a finite collection of objects indexed by a set of arbitrary immutable keys. There is currently only one built-in mapping type: Dictionary Mappings.

Dictionary mappings are effectively associative arrays with access notation: dic[key]. Keys are numbers or strings. Dictionary mappings are created with literals or the dict([arg]) constructor:

# These make dictionary mapping object of {1: 's', 't': 7}:
d1 = {1: 's', 't': 7} # Literal
d2 = dict({1: 's', 't': 7}) # constructor with literal
d3 = dict([(1, 's'), ('t', 7)]) # constructor with list of key-value tuples
d4 = dict(1='s', t=7) # errs. This format only works if keys are strings
d4 = dict(s=1, t=7) # Literal: {'s': 1, 't': 7}
d5 = dict(zip((1, 't'), ['t', 7])) # constructor with a zip function
d6 = dict([[1, 's'], ['t', 7]]) # constructor with list of key-value lists

Here are operations available to dictionary mapping types: len(d), d[key], d[key] = value, del d[key], key in d, key not in d, iter(d), clear(), copy(), fromkeys(seq[, value]), get(key[, default]), has_key(key), items(), iteritems(), iterkeys(), itervalues(), keys(), pop(key[, default]), popitem(), setdefault(key[, default]), update([other]), values(), viewitems(), viewkeys(), viewvalues().

>>> d = {1: 's', 't': 7} # Literal
>>> d['t'] = 8
>>> del d[1]
>>> d
{'t': 8}
>>> d['u'] = 6
>>> d.keys()
['u', 't']
>>> for a, b in d.iteritems(): # unpacking
...     print a, b
...
u 6
t 8

Flow Control

The if statement. An if...elif...elif... sequence is like a switch or case statement in other languages.

>>> i = 9 
>>> if i < 0:
...    i = 0
...    print 'Negative. Now zero.'
... elif i == 0:
...    print 'Zero'
... elif i == 1:
...    print 'One'
... else:
...    print 'Positive'
...
Positive

The while statement is used for repeated execution as long as an expression is true. This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates. A break statement executed in the first suite terminates the loop without executing the else clauses suite. A continue statement executed in the first suite skips the rest of the suite and goes back to testing the expression.

while x > 7:
    print x
else:
    print 'foo'

The for statement in Python assumes iteration over items in a sequence in the order they appear. The break and continue statements work just like in the while statement.

>>> for i in range(1, 3):
...    print i
...
1
2

>>> a = ['a', 'ah', 'choo']
>>> for s in a:
...    print s, len(s)
...
a 1
ah 2
choo 4

>>> for i, v in enumerate(['fe', 'fi', 'fo'])
...     print i, v
...
0 fe
1 fi
2 fo

Avoid infinite loops and similar problems by iterating through a copy while modifying the original sequence.

>>> a = ['a', 'ah', 'choo']
>>> for x in a[:]:
...    if len(x) > 2: a.insert(0, x)
...
>>> a
['choo', 'a', 'ah', 'choo']

The range(([start], stop[, step]) function generates sequence. start defaults to 0. step defaults to 1. The last item of the generated sequence is never stop.

>>> range(6) # 0-index
[0, 1, 2, 3, 4, 5]
>>> range(3, 6) # Set the start and end of a sequence
[3, 4, 5]
>>> range(3, 10, 3) # Set the increment/step
[3, 6, 9]
>>> range(4, -5, -2) # Negative step
[4, 2, 0, -2, -4]

In Python 3.*, there are slight differences.

>>> range(6) # 0-index
range(0, 6)
>>> list(range(6)) # 0-index
[0, 1, 2, 3, 4, 5]

The break statement breaks out of the innermost for or while loop.

The continue statement continues to the next iteration of the loop.

The pass statement does nothing. It is used in places where a statement is syntactically required.

while True:
    pass # Wait for interrupt (Ctrl+C)

class AnEmptyClass:
    pass

def myMethod():
    pass # Code later

Functional Programming

Functional programming may be considered a type of flow control. There are three built-in functions for functional programming.

filter(function, sequence) returns a sequence consisting of those items from the sequence for which function(item) is true. If sequence is a string or tuple, the result will be of the same type; otherwise, it is always a list.

>>> r = range(4)
>>> def a(x): return x % 2
...
>>> filter(a, r)
[1, 3]

map(function, sequence) calls function(item) for each item in sequence, and returns a list of the return values.

>>> map(a, r)
[0, 1, 0, 1]
# Functions with multiple parameters can use multiple sequences:
>>> def b(x, y): return x + y
...
>>> map(b, r, r)
[0, 2, 4, 6]

reduce(function, sequence) calls function(a, b) for the first two items in the sequence, then on the result and the 3rd item, and so on.

>>> reduce(b, r)
6 # Same as ((0+1)+2)+3

List comprehensions have this sort of syntax: [Expression for item in sequence].

>>> a = [3, 4, 5]
>>> [x * x for x in a]
[9, 16, 25]
>>> [x * x for x in a if x < 5]
[9, 16]
>>> [(x, x * x) for x in a]
[(3, 9), (4, 16), (5, 25)]

Functions

In Python a function is defined with the def keyword.

>>> def foo(n):
...     print n
...
>>> foo(3)
3
>>> f = foo
>>> f(4)
4
>>> def f():
...     pass
...
>>> f()
>>> print f() # Shows that something is always returned
None
# return without an expression, or falling off a function also returns None

Funtion arguments and variables set in functions are local.

a_var = 10
b_var = 15
e_var = 25
 
def a_func(a_var):
    print("in a_func a_var = ", a_var) # local!
    b_var = 100 + a_var # local!
    d_var = 2 * a_var # local
    print("in a_func b_var = ", b_var)
    print("in a_func d_var = ", d_var)
    print("in a_func e_var = ", e_var) # global!
    return b_var + 10
 
c_var = a_func(b_var)
 
print("a_var = ", a_var)
print("b_var = ", b_var)
print("c_var = ", c_var)
print("d_var = ", d_var) # errs!

Arguments for functions.

def f(required) # Call as f(x)
def f(optional = 3) # Call as f() or f(x)
def f(req, opt = 3) # Call as f(x) or f(x, y) or f(x, opt = y)

# The order of arguments can be changed if keyworded:
def f(age, sex='f') # Can call as f(sex='m', age=9)

# For a variable # of non-keyworded arguments use *args:
def f(req, *args):
    for arg in args:
        print arg
f(1, 2, 3, 4)
args = (2, 3, 4)
f(1, *args)

# For a variable # of keyworded arguments use **kwargs:
def f(req, **kwargs):
    for key in kwargs:
        print "kw: %s, value: %s" % (key, kwargs[key])
f(1, 'a'=2, 'b'=3)
kwargs = {'a'=2, 'b'=3}
f(1, **kwargs)

# Mix up the args:
def f(req, *args, *kwargs):
    print req
    for arg in args:
        print arg
    for key in kwargs:
        print "kw: %s, value: %s" % (key, kwargs[key])
f(1, 2, 3, 'a'=4, 'b'=5)

Lambda forms (lambda expressions) are created by using the lambda keyword. It essentially defines and uses an anonymous function right there.

# Syntax: lambda args: expression
# Same as:
def anon(args):
    return expression

Modules and Libraries

Python is famous for its ability to load modules or libraries of code. Some libraries are built into the language (See http://docs.python.org/library/.), while others are made by other folks.

In this example we import the built in calendar module (i.e. the calendar.py file):

import calendar
year = int(input("Year: "))
calendar.prcal(year)

In this example we import specific funtions from modules:

from calendar import prcal
from time import time, ctime
year = int(input("Year: "))
prcal(year)
print("Time:", ctime(time()))

Links

Links that lead to off-site pages about Python.

Official

python.org. The official site.

Wikipedia and Wikibooks

Chicago

Web Application Frameworks

Web application frameworks for Python.

Tutorials

Books

Miscellany

Page Modified: (Hand noted: 2011-04-29 14:18:00Z) (Auto noted: 2014-01-02 22:19:25Z)