What You Need To Know About Python

Chris Calloway

University of North Carolina Marine Sciences

October 9, 2008

Copyright 2008 Chris Calloway - All Rights Reserved

About This Talk

If you already know Python, go find another talk.

About This Talk

Many people at Plone Conference don't know Python.

About This Talk

This talk is for Plone Conference people who don't know Python.

About This Talk

This talk will move extremely fast.

About This Talk

About one slide every twelve seconds.

About This Talk

Look at the code.

About This Talk

Listen to the descriptions.

About This Talk

This talk will not teach you Python.

About This Talk

This talk will teach you what you need to know about Python.

About This Talk

Only by study and practice will you learn Python.

About This Talk

This talk will allow you to judge whether learning Python is right for you.

About This Talk

You will likely be dizzy and confused by the end of this talk.

About This Talk

That's OK.

About This Talk

You will know the scope of what you may want to learn by the end of this talk.

About This Talk

And you can follow along at your own pace later.

About This Talk

http://trizpug.org/Members/cbc/wyntkap/wyntkap.html

What Is Python?

What Is Python?

What Is Python?

The Interpreter: the Python Prompt

> python

The Interpreter: the Python Prompt

The Interpreter: the Python Prompt

> python
>>>

The Python prompt is waiting for you!

The Interpreter: the Python Prompt

> python
>>> 1 + 2 * 3

This is an example of a Python expression.

The Interpreter: the Python Prompt

> python
>>> 1 + 2 * 3
7
>>>

Evaluating an expression at the Python prompt results in the interpreter representing the value of the expression.

The Interpreter: the Python Prompt

> python
>>> 1 + 2 * 3
7
>>> print "OK"

This is an example of a Python print statement.

The Interpreter: the Python Prompt

> python
>>> 1 + 2 * 3
7
>>> print "OK"
OK
>>>

Executing a Python statement involves one of more Python keywords.

The Interpreter: the Python Prompt

>>> help("keywords")

Evaluate the built-in help() function with the argument "keywords" to see a list of all keywords known to your Python interpreter.

The Interpreter: the Python Prompt

>>> help("keywords")

Here is a list of the Python keywords.  Enter any keyword to get more help.

and                 else                import              raise
assert              except              in                  return
break               exec                is                  try
class               finally             lambda              while
continue            for                 not                 yield
def                 from                or                  
del                 global              pass                
elif                if                  print                

>>>

Python is a simple language with very few keywords compared to other languages.

The Interpreter: the Python Prompt

>>> ^D
>

Type your system's end of file character to end your session at the Python prompt.

The Interpreter: Python Scripts

Contents of myscript.py:

print "OK"

The Interpreter: Python Scripts

> python myscript.py
OK
>

The Interpreter: Python Scripts

> python path/to/myscript.py
OK
>

Use a relative path if myscript.py is in a subdirectory of the current directory.

The Interpreter: Python Scripts

> python /path/to/myscript.py
OK
>

You may always use an absolute path to your script.

The Interpreter: Python Scripts

Contents of myscript.py:

#! /usr/bin/python

print "OK"

The "she-bang" line tells a non-Windows OS to interpret the file with a specific Python interpreter.

The Interpreter: Python Scripts

Contents of myscript.py:

#! /usr/bin/env python

print "OK"

The Interpreter: Python Scripts

non-Windows:

> chmod +x myscript.py
> ./myscript.py
OK
>

The script must be executable to use the she-bang line.

The Interpreter: Python Scripts

Windows:

> ftype Python.Script="C:\Python24\python.exe" "%1" "%*"
> assoc .py=Python.Script
> myscript.py
OK
>

The Interpreter: Python Scripts

Windows:

> ftype Python.Script="C:\Python24\python.exe" "%1" "%*"
> assoc .py=Python.Script
> myscript.py
OK
>

The Interpreter: Python Scripts

Windows:

> set PATHEXT=%PATHEXT%;.py
> myscript
OK
>

Set the PATHEXT to include .py file extensions in the list of extensions with interpreters.

The Interpreter: Python Scripts

The safest way on any platform:

> /full/path/to/python /full/path/to/myscript.py
OK
>

The Compiler

> python
>>> import myscript
OK
>>>

The Compiler

> python
>>> import myscript
OK
>>> import myscript
>>>

Each subsequent reload of the compiled module skips the interpretation step.

The Compiler

> rm -f myscript.py # del myscript.py on Windows
> python myscript.pyc
OK
> python
>>> import myscript
OK
>>>

The Compiler

> ls -l myscript.pyc
-rw-r--r--  1 cbc  trizpug  110 Sep 14 16:00 myscript.pyc
> vi myscript.py
> ls -l myscript.py
-rw-r--r--  1 cbc  trizpug  20  Sep 14 16:01 myscript.py
> python
>>> import myscript
OK Already
>>> ^D
> ls -l myscript.pyc
-rw-r--r--  1 cbc  trizpug  118 Sep 14 16:02 myscript.pyc

The Compiler

The Compiler

The Compiler

Just try it!

What Is Python?

What Is Python?

Everything Is An Object

In Python, everything is an object.

Everything Is An Object

Whenever you ever come across something in Python which makes you ask:

"What is this?"

Your first correct answer is, "an object."

What Is an Object?

What Are Attributes?

Whenever you ever come across something in Python which makes you ask:

"What is this?"

Your first correct answer is, "an object."

OK, Smarty-Pants, What Is An Attribute?

What Is An Attribute?

Accessing Attributes

Accessing Attributes

>>> "OK"
'OK'
>>> print "OK"
OK
>>>

Your old friend, the string object "OK."

Accessing Attributes

>>> "OK".__doc__
'str(object) -> string\n\nReturn a nice string representation of the object.
\nIf the argument is a string, the return value is the same object.'
>>>

Accessing Attributes

>>> "OK".__doc__
'str(object) -> string\n\nReturn a nice string representation of the object.
\nIf the argument is a string, the return value is the same object.'
>>> print "OK".__doc__
str(object) -> string

Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
>>>

Accessing Attributes

>>> "OK".lower
<built-in method lower of str object at 0x69880>
>>>

All string objects also have a method named lower.

Calling Methods

Calling Methods

>>> "OK".lower
<built-in method lower of str object at 0x69880>
>>> "OK".lower()
'ok'
>>>

Calling the lower method evaluates to another string!

Calling Methods

>>> "OK".lower
<built-in method lower of str object at 0x69880>
>>> "OK".lower()
'ok'
>>> print "OK".lower()
ok
>>>

And we may render the string returned by the lower method into a nicer visual representation with a print statement.

Accessing Attributes

Accessing Attributes

>>> print "OK".lower.__doc__
S.lower() -> string

Return a copy of the string S converted to lowercase.
>>>

The string "OK" has a lower method, which has a __doc__ attribute, which may be rendered with a print statement.

What Is Python?

What is Typing?

What is Typing?

>>> type("OK")
<type 'str'>
>>> type(type("OK"))
<type 'type'>
>>> 

What is Typing?

>>> type("OK")
<type 'str'>
>>> type(type("OK"))
<type 'type'>
>>>  type(type("OK"))("OK")
<type 'str'>
>>>

What is Typing?

>>> type("OK")
<type 'str'>
>>> type("OK")("OK")
'OK'
>>> type("OK")(1)
'1'
>>>

What is Typing?

>>> type("OK")
<type 'str'>
>>> type("OK")("OK")
'OK'
>>> type("OK")(1)
'1'
>>>

What is Typing?

>>> dir("OK")
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__',
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode',
'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha',
'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']
>>>

The built-in dir() function return a list of the names of the attributes of the object passed as its argument.

What is Typing?

>>> dir("OK")
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__',
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode',
'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha',
'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']
>>>

The list will contain at least all the attributes required for an object of the argument's type.

What is Typing?

>>> dir("OK")
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__',
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode',
'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha',
'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']
>>>

Duck typing: "If it walks like a duck, and quacks like a duck, then it's a duck."

Everything Is An Object

Whenever you ever come across something in Python which makes you ask:

"What is this?"

Your first correct answer is, "an object."

Everything Is An Object

Your next question should then be:

"What type of object is this?"

Numeric Types

Numeric Types

>>> 3
3
>>> type(3)
<type 'int'>
>>> 076
62
>>> 0xAE
174
>>>

Numeric Types

>>> type("3")
<type 'str'>
>>> int("3")
3
>>>

The built-in int() type object creates a new integer object from a string or floating point argument.

Numeric Types

>>> dir(3)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__',
'__delattr__', '__div__', '__divmod__', '__doc__', '__float__',
'__floordiv__', '__getattribute__', '__getnewargs__', '__hash__',
'__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__',
'__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__',
'__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__',
'__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__',
'__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__',
'__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__',
'__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__']
>>>

The attributes of an int object are mostly methods concerned with what happens when an integer is used in an arithmetic operation.

Numeric Types

>>> print int(3).__add__.__doc__
x.__add__(y) <==> x+y
>>> int(3).__add__(2)
5
>>> 3 + 2
5
>>>

For instance, the __add__() method of int objects is invoked whenever an integer is the first operand for the addition ("+") operator.

Special Methods

Numeric Types

>>> 9 / 4
2
>>>

Numeric Types

>>> 9 / 4
2
>>> 9 % 4
1
>>>

Numeric Types

>>> type(3.)
<type 'float'>
>>> type(3e10)
<type 'float'>
>>> 3.
3.0
>>> 3e10
30000000000.0
>>>

Numeric Types

>>> 1e-6
9.9999999999999995e-07
>>>

Because storing floating point numbers involves converting decimal literals to binary mantissae of limited precision, the accuracy of floating point operations is not perfect.

Numeric Types

>>> 1e-6
9.9999999999999995e-07
>>> 1e-6 == 0.000001
True
>>>

However, the accuracy is happily consistent.

Numeric Types

>>> float(3)
3.0
>>> float("3e10")
30000000000.0
>>>

The built-in float() type object creates a new float object from a string or integer argument.

Numeric Types

>>> 123456789012345678901234567890L
123456789012345678901234567890L
>>>

Numeric Types

>>> 2 ** 31
2147483648L
>>>

Numeric Types

>>> 3/3.0
1.0
>>> 3L + 3.0
6.0
>>>

Mixing integers or long objects with float objects in numeric expressions results in float objects.

Numeric Types

>>> 3 == 3.0
True
>>> 3L == 3.0
True
>>>

Comparison between numeric objects of different types produces common sense results.

Numeric Types

>>> 1+1J
(1+1j)
>>> 3.5-2.7j
(3.5-2.7j)
>>>

Numeric Types

>>> 2 * 3 + 4j
(6+4j)
>>> 2 * (3 + 4j)
(6+8j)
>>>

Use parentheses to disambiguate the order of operations in expressions involving complex number objects.

Numeric Types

>>> (3 + 4j).real
3.0
>>> (3 + 4j).imag
4.0
>>>

Complex objects have real and imag attributes.

Numeric Types

>>> True
True
>>> type(True)
<type 'bool'>
>>> False
False
>>> type(False)
<type 'bool'>
>>>

Numeric Types

>>> bool(0)
False
>>> bool(-5)
True
>>> bool(0+1j)
True
>>> bool("")
False
>>> bool("OK")
True
>>> bool("OK".lower)
True
>>>

Any Python object may be evaluated for its truth value using the bool() built-in type object.

Numeric Operators

x + ysum of x and y
x - ydifference of x and y
x * yproduct of x and y
x / yquotient of x and y
x // y(floored) quotient of x and y
x % yremainder of x / y
-xx negated
+xx unchanged
x ** yx to the power y

Numeric Operators: Bit-wise

x | ybitwise or of x and y
x ^ ybitwise exclusive or of x and y
x & ybitwise and of x and y
x << nx shifted left by n bits
x >> nx shifted right by n bits
∼xthe bits of x inverted

Numeric Operators: Comparison

<strictly less than
<=less than or equal
>strictly greater than
>=greater than or equal
==equal value (equivalency)
!=not equal

All comparison operations result in a True or False Boolean value.

Identifiers and Binding

Identifiers and Binding

>>> a = 3
>>> a
3
>>> 

Identifiers and Binding

>>> b               
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'b' is not defined
>>> 

Identifiers and Binding

>>> a = 3
>>> a
3
>>> type(a)
<type 'int'>
>>>

Identifiers and Binding

>>> a = 3.0
>>> type(a)
<type 'float'>
>>>

Identifiers and Binding

>>> a = b = c = 3
>>> a
3
>>> b
3
>>> c
3
>>>

An object may be bound to several identifiers simultaneously in one assignment statement.

Augmented Assignment

x += ysame as x = x + y
x -= ysame as x = x - y
x *= ysame as x = x * y
x /= ysame as x = x / y
x //= ysame as x = x // y
x **= ysame as x = x ** y
x %= ysame as x = x % y
x &= ysame as x = x & y
x |= ysame as x = x | y
x ^= ysame as x = x ^ y
x >>= ysame as x = x >> y
x <<= ysame as x = x << y

What Is Python?

What Is Python?

What Is Python?

The combination of strong and dynamic typing is described as duck typing.

If it walks like a duck, and it quacks like a duck, then it's a duck.

Identifiers and Binding

>>> a = 3
>>> b = a
>>> c = b
>>> c
3
>>>

An object may be bound to many identifiers.

Identifiers and Binding

>>> a = 3
>>> b = a
>>> c = b
>>> c
3
>>> a = 5
>>> b
3
>>>

Rebinding one identifier to another object does not rebind the other identifiers.

Sequence Types

Sequence Types

Sequence Types

Sequence Types

>>> "OK Already"[3]
'A'
>>>

Elements in a sequence are indexed by the subscription operator ("[]").

Sequence Types

>>> len("OK Already")  
10
>>> 

The built-in len() function evaluates the number of elements in a sequence.

Sequence Types

>>> "OK Already"[10]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IndexError: string index out of range
>>>

Indexing beyond the end of a sequence raises an IndexError Exception.

Sequence Types

>>> "OK Already"[-7]
'A'
>>>

Negative indices count back from the last element in the sequence.

Sequence Types

>>> "OK Already"[-11] 
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IndexError: string index out of range
>>>

Negative indexing before the beginning of a sequence raises an IndexError Exception.

Sequence Types

>>> "OK Already"[-1]
'y'
>>>

This makes it easy to find the last element in a sequence.

Sequence Types

>>> "OK Already"[1:4]
'K A'
>>>

Sequence Types

>>> "OK Already"[1:7:2]
'KAr'
>>>

Slice objects may have an optional third step value.

Sequence Types

>>> "OK Already"[3:20]
'Already'
>>>

Slicing beyond the end of a sequence does not raise an IndexError Exception.

Sequence Types

>>> "OK Already"[-7:-2]
'Alrea'
>>>

Negative indices work fine with slice objects.

Sequence Types

>>> "OK Already"[7:2]
''
>>>

A slice object subscription which ends before it begins evaluates to an empty sequence.

Sequence Types

>>> "OK Already"[3:]
'Already'
>>>

Omitting the stop value from a slice object is the same as specifying the end of the sequence.

Sequence Types

>>> "OK Already"[:2]
'OK'
>>>

Omitting the start value from a slice object is the same as specifying the beginning of the sequence.

Strings

Strings

Escaped characters start with a backslash:

\\Backslash (\)\nASCII Linefeed
\'Single quote (')\rASCII Carriage Return
\"Double quote (")\tASCII Horizontal Tab
\aASCII Bell\vASCII Vertical Tab
\bASCII Backspace\oooCharacter with octal value ooo
\fASCII Formfeed\xhhCharacter with hex value hh

Strings

>>> print '\''
'
>>> 

Print an escaped single quote.

Strings

>>> print '\''
'
>>> print "The time is \"now.\""
The time is "now."
>>> 

Print a couple of escaped double quotes.

Strings

>>> print '\''
'
>>> print "The time is \"now.\""
The time is "now."
>>> print "Now\tis\nbetter\fthan\b\bnever."
Now     is
better
      thnever.
>>> 

Print some carriage control characters.

Strings

>>> print '\''
'
>>> print "The time is \"now.\""
The time is "now."
>>> print "Now\tis\nbetter\fthan\b\bnever."
Now     is
better
      thnever.
>>> print r"Now\tis\nbetter\fthan\b\bnever."
Now\tis\nbetter\fthan\b\bnever.
>>> 

Print a raw string with unescaped escaped characters.

Strings

Contents of myscript.py:

#!/usr/bin/env python

a = """
    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    """

print a

An example of a multiline string.

Strings

> python myscript.py

    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    
>

Strings

Contents of myscript.py:

#!/usr/bin/env python

a = """
    Beautiful is better than ugly.
    Explicit is better\fthan implicit.
    Simple is better than complex.
    """

print a

An example of a multiline string with an escaped form feed character.

Strings

> python myscript.py

    Beautiful is better than ugly.
    Explicit is better
                      than implicit.
    Simple is better than complex.
    
>

Strings

Contents of myscript.py:

#!/usr/bin/env python

a = r"""
    Beautiful is better than ugly.
    Explicit is better\fthan implicit.
    Simple is better than complex.
    """

print a
An example of a raw multiline string with an unescaped form feed character.

Strings

> python myscript.py

    Beautiful is better than ugly.
    Explicit is better\fthan implicit.
    Simple is better than complex.
    
>

Tuples

Tuples

>>> tuple("OK")
('O', 'K')
>>> 42, 23, "OK"
(42, 23, 'OK')
>>>

Tuples

>>> a = 42, 23, 'OK'
>>> a[1]
23
>>> a[-1]
'OK'
>>> a[1:]
(23, 'OK')
>>> len(a)
3
>>>

Tuples

Tuple Packing

>>> a = 42, 23, "OK"
>>> x, y, z = a
>>> x
42
>>> y
23
>>> z
'OK'
>>>

Tuple Packing

>>> a = 42, 23, "OK"
>>> x, y = a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
>>> w, x, y, z = a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 3 values to unpack
>>>

There must be equal number of elements to unpack on both sides of the assignment.

Tuple Packing

>>> a = 1
>>> b = 2
>>> b, a = a, b
>>> a
2
>>> b
1
>>>

Cool Python trick!

String Formatting

>>> "%s depends a lot on %s." % ('Python', 'tuples')
'Python depends a lot on tuples.'
>>> 

String Formatting

dSigned integer decimalfFloating point decimal format
iSigned integer decimalFFloating point decimal format
oUnsigned octalgFloating point format. Uses exponential format if exponent is greater than -4 or less than precision, decimal format otherwise
uUnsigned decimalGFloating point format. Uses exponential format if exponent is greater than -4 or less than precision, decimal format otherwise
xUnsigned hexadecimal (lowercase)cSingle character (accepts integer or single character string)
XUnsigned hexadecimal (uppercase)rString (converts any python object using repr())
eFloating point exponential format (lowercase)sString (converts any python object using str()
EFloating point exponential format (uppercase)%No argument is converted, results in a "%" character in the result

String Formatting

>>> "The cost is %.2f dollars." % (100,)
'The cost is 100.00 dollars.'
>>> 

Conversion specifiers may have a precision modifier for floating point conversions.

String Formatting

>>> "The cost is %10.2f dollars." % (100,)
'The cost is     100.00 dollars.'
>>>

Conversion specifiers may have a minimum field width modifier.

String Formatting

>>> "The cost is %*.*f dollars." % (15, 4, 100,)
'The cost is        100.0000 dollars.'
>>>

Both minimum field width and precision may be read from the tuple object.

String Formatting

>>> "The cost is %0*.*f dollars." % (15, 4, 100,)
'The cost is 0000000100.0000 dollars.'
>>>

Numeric conversions may be zero padded on the left to the minimum field width with a "0" conversion flag.

String Formatting

>>> "The cost is %-*.*f dollars." % (15, 4, 100,)
'The cost is 100.0000        dollars.'
>>>

Conversions may be left justified in the minimum field width width with a "-" conversion flag.

String Formatting

>>> "The cost is %+.2f dollars." % (100,)
'The cost is +100.00 dollars.'
>>> "The cost is %+.2f dollars." % (-100,)
'The cost is -100.00 dollars.'
>>>

Conversions may force a sign character for numeric conversions of both positive and negative values with a "+" conversion flag.

Lists

Lists

>>> list((42, 23, "OK"))
[42, 23, 'OK']
>>> [42,23,"OK"]
[42, 23, 'OK']
>>>

Lists

>>> a = [42, 23, 'OK']
>>> a[1]
23
>>> a[-1]
'OK'
>>> a[1:]
(23, 'OK')
>>> len(a)
3
>>>

Lists

List Operations

>>> a = [2.0, 'OK', 3+4j, (42, 23, 'OK'), [1,2,3]]
>>> a
[2.0, 'OK', (3+4j), (42, 23, 'OK'), [1, 2, 3]]
>>> a[1]
'OK'
>>> a[1] = 2**31
>>> a
[2.0, 2147483648L, (3+4j), (42, 23, 'OK'), [1, 2, 3]]
>>>

To replace an element in a list object, put the subscription operator on the left hand side of an assignment statement.

List Operations

>>> a
[2.0, 2147483648L, (3+4j), (42, 23, 'OK'), [1, 2, 3]]
>>> del a[2]
>>> a
[2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3]]
>>> 

To remove an element from a list object, use the del keyword with the subscription operator.

List Operations

>>> a
[2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3]]
>>> a.append("spam")
>>> a
[2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam']
>>> 

The None Object

>>> None
>>> type(None)
<type 'NoneType'>
>>> 

The None Object

>>> None
>>> type(None)
<type 'NoneType'>
>>> dir(None)
['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__',
'__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__str__']
>>> a = None
>>> a
>>> 

List Operations

>>> a
[2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam']
>>> a.extend("OK")
>>> a
[2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'O', 'K']
>>> a.extend((1,2,3))
>>> a
[2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'O', 'K', 1, 2, 3]
>>> a.extend(['python','zope','plone','grok'])
>>> a
[2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'O', 'K', 1, 2, 3,
'python', 'zope', 'plone', 'grok']
>>>

Use the extend() method to add all the elements from another sequence to the end of a list object.

List Operations

>>> a
[2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'O', 'K', 1, 2, 3,
'python', 'zope', 'plone', 'grok']
>>> del a[5:10]
>>> a
[2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'python', 'zope',
'plone', 'grok']
>>> 

slice objects as subsciptions may remove entire slices of a list object using the del keyword.

List Operations

>>> a
[2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'python', 'zope',
'plone', 'grok']
>>> a.insert(0,3e6)
>>> a
[3000000.0, 2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'python',
'zope', 'plone', 'grok']
>>>

The insert() method of list objects allows you to insert an arbitrary object before any index which already exists.

List Operations

>>> a
[3000000.0, 2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'python',
'zope', 'plone', 'grok']
>>> a.insert(25,3e6)
>>> a
[3000000.0, 2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'python',
'zope', 'plone', 'grok', 3000000.0]
>>> a.insert(50,3e6)
>>> a
[3000000.0, 2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'python',
'zope', 'plone', 'grok', 3000000.0, 3000000.0]
>>> 

Or at the end of a list object if the index does not already exist.

List Operations

>>> a
[3000000.0, 2.0, 2147483648L, (42, 23, 'OK'), [1, 2, 3], 'spam', 'python',
'zope', 'plone', 'grok', 3000000.0, 3000000.0]
>>> a[3:-1] = 'sprint'
>>> a
[3000000.0, 2.0, 2147483648L, 's', 'p', 'r', 'i', 'n', 't', 3000000.0]
>>>

List Operations

>>> a
[3000000.0, 2.0, 2147483648L, 's', 'p', 'r', 'i', 'n', 't', 3000000.0]
>>> a[3:-1] = ('sprint',)
>>> a
[3000000.0, 2.0, 2147483648L, 'sprint', 3000000.0]
>>>

To replace a slice of a list object with a sequence instead of the elements of a sequence, wrap the replacement sequence in another sequence.

List Operations

>>> a
[3000000.0, 2.0, 2147483648L, 'sprint', 3000000.0]
>>> a[3:] = ('plone',)
>>> a
[3000000.0, 2.0, 2147483648L, 'plone']
>>> 

To replace a slice of a list object through to the end of the list, omit the stop index of the slice object.

List Operations

>>> a
[3000000.0, 2.0, 2147483648L, 'plone']
>>> b = a[:]
>>> b
[3000000.0, 2.0, 2147483648L, 'plone']
>>>

You may make a copy of a list object by using a slice object on the right hand side of an assigment statement where both the start and stop indices have been omitted.

List Operations

>>> a
[3000000.0, 2.0, 2147483648L, 'plone']
>>> b = a[:]
>>> b
[3000000.0, 2.0, 2147483648L, 'plone']
>>> a == b
True
>>>

The list object and its copy have equivalent value.

List Operations

>>> a
[3000000.0, 2.0, 2147483648L, 'plone']
>>> b = a[:]
>>> b
[3000000.0, 2.0, 2147483648L, 'plone']
>>> a == b
True
>>> a is b
False
>>>

But the original object and its copy are two distinctly different objects.

List Operations

>>> id(a)
2446960
>>> id(b)
2386320
>>>

The original object and its copy have different object id values.

List Operations

>>> a
[3000000.0, 2.0, 2147483648L, 'plone']
>>> b
[3000000.0, 2.0, 2147483648L, 'plone']
>>> a[0] = 'python'
>>> b
[3000000.0, 2.0, 2147483648L, 'plone']
>>> b[0] = 'zope'
>>> a
['python', 2.0, 2147483648L, 'plone']
>>>

The original object and its copy are independent of one another. A change to one does not affect the other.

List Methods

>>> dir([])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__',
'__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__',
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__',
'__setslice__', '__str__', 'append', 'count', 'extend', 'index',
'insert', 'pop', 'remove', 'reverse', 'sort']
>>> 

You have already seen the append, extend, and insert methods of list objects.

List Methods

>>> a = ['bacon','spam','eggs','spam','toast','spam']
>>> a.count('spam')
3
>>>

The count() method returns the number of occurrences of an object in a list object.

List Methods

>>> a              
['bacon', 'spam', 'eggs', 'spam', 'toast', 'spam']
>>> a.index('spam')
1
>>>

The index() method returns the index of the first occurrence of an object in a list object.

List Methods

>>> a
['bacon', 'spam', 'eggs', 'spam', 'toast', 'spam']
>>> a.pop()
'spam'
>>> a
['bacon', 'spam', 'eggs', 'spam', 'toast']
>>> a.pop(2)
'eggs'
>>> a
['bacon', 'spam', 'spam', 'toast']
>>>

List Methods

>>> a
['bacon', 'spam', 'spam', 'toast']
>>> a.remove('spam')
>>> a
['bacon', 'spam', 'toast']
>>> a.remove('spam')
>>> a
['bacon', 'toast']
>>> 

List Methods

>>> a = ['first', 2, 3.0, 4L, 5+0j]
>>> a.reverse()
>>> a
[(5+0j), 4L, 3.0, 2, 'first']
>>>

List Methods

>>> a = ['one', 42, 'abc', 23, 'two']
>>> a.sort()
>>> a
[23, 42, 'abc', 'one', 'two']
>>>

Tuple Methods?

>>> dir(())
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__',
'__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__str__']
>>>

String Methods

>>> dir("")
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__',
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode',
'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha',
'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']
>>>

str objects are immutable, too.

String Methods

>>> dir("")
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__',
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode',
'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha',
'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']
>>>

But str objects have lots of regular methods!

String Methods

>>> dir("")
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__',
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode',
'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha',
'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title', 'translate', 'upper', 'zfill']
>>>

Most of which return new str objects.

String Methods

>>> 'pYtHoN'.capitalize()
'Python'
>>>

Return a copy of the str object with only the first character capitalized.

String Methods

>>> 'python'.center(20)
'       python       '
>>> 'python'.center(20,'*')
'*******python*******'
>>>

String Methods

>>> 'python python python'.count('python')
3
>>> 'python python python'.count('python',6)
2
>>> 'python python python'.count('python',6,15)
1
>>>

String Methods

>>> 'Python loves strings.'.endswith('strings')
False
>>> 'Python loves strings.'.endswith('strings.')
True
>>>

Return True if the str object ends with the specified suffix str object, False otherwise.

String Methods

>>> 'Python loves strings.'.endswith(('strings.','tuples.','lists.'))
True
>>> 'Python loves strings.'.endswith('strings.',6)
True
>>> 'Python loves strings.'.endswith('strings.',6,10)
False
>>>

String Methods

>>> 'Python loves strings.'.startswith('python')
False
>>> 'Python loves strings.'.startswith('Python')
True
>>>

Return True if the str object starts with the specified prefix str object, False otherwise.

String Methods

>>> 'I\tlove\tPython.'.expandtabs()
'I       love    Python.'
>>> 'I\tlove\tPython.'.expandtabs(6)
'I     love  Python.'
>>>

String Methods

>>> 'To python, or not to python'.find('python')
3
>>> 'To python, or not to python'.find('python',5)
21
>>> 'To python, or not to python'.find('python',5,21)
-1
>>>

String Methods

>>> 'To python, or not to python'.index('python')
3
>>> 'To python, or not to python'.index('python',5)
21
>>> 'To python, or not to python'.index('python',5,21)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>>

String Methods

>>> 'python123'.isalnum()
True
>>> 'python 123'.isalnum()
False
>>> ''.isalnum()
False
>>> 

Return True if all characters in the str object are alphanumeric and there is at least one character. False otherwise.

String Methods

>>> 'python1'.isalpha()
False
>>> '123'.isdigit()
True
>>> 'python'.islower()
True
>>> 'python'.isupper()
False
>>> '\t\n   \f'.isspace()
True
>>> 'Big Newspaper Headline'.istitle()
True
>>>

String Methods

>>> 'python in a nutshell'.title()
'Python In A Nutshell'
>>>

Line Continuation

String Methods

>>> ' '.join(['A','day','without','Python','is','like',
...           'a','day','without','sunshine.'])
'A day without Python is like a day without sunshine.'
>>>

String Methods

>>> ''.join(['A','day','without','Python','is','like',
...           'a','day','without','sunshine.'])
'AdaywithoutPythonislikeadaywithoutsunshine.'
>>>

String Methods

>>> print '\n'.join(['A','day','without','Python','is','like',
...                  'a','day','without','sunshine.'])
A
day
without
Python
is
like
a
day
without
sunshine.
>>>

String Methods

>>> 'python'.ljust(20)
'python              '
>>> 'python'.ljust(20,'*')
'python**************'
>>>

String Methods

>>> 'pYtHoN'.lower()
'python'
>>> 'pYtHoN'.upper()
'PYTHON'
>>>

Return a copy of the str object converted to upper or lower rcase.

String Methods

>>> '   python   '.lstrip()
'python   '
>>> '\t\n\tpython\t\n\t'.lstrip()
'python\t\n\t'
>>> 'lalapythonlala'.lstrip('la')
'pythonlala'
>>> 

String Methods

>>> '   python   '.strip()
'python'
>>> '\t\n\tpython\t\n\t'.strip()
'python'
>>> 'lalapythonlala'.strip('la')
'python'
>>> 

String Methods

>>> 'python2.4 python2.4 python2.4'.replace('python2.4','python2.5')
'python2.5 python2.5 python2.5'
>>> 'python2.4 python2.4 python2.4'.replace('python2.4','python2.5',2)
'python2.5 python2.5 python2.4'
>>>

String Methods

String Methods

>>> 'python\t\npython\t\npython'.split()
['python', 'python', 'python']
>>> 'python**python**python'.split('**')
['python', 'python', 'python']
>>> 'python**python**python'.split('*',1)
['python', '*python**python']
>>> 

String Methods

>>> """
... Beautiful is better than ugly.
... Explicit is better than implicit.
... Simple is better than complex.
... """.splitlines()
['', 'Beautiful is better than ugly.',
'Explicit is better than implicit.',
'Simple is better than complex.']
>>>

String Methods

>>> """
... Beautiful is better than ugly.
... Explicit is better than implicit.
... Simple is better than complex.
... """.splitlines(True)
['\n', 'Beautiful is better than ugly.\n',
'Explicit is better than implicit.\n',
'Simple is better than complex.\n']
>>>

String Methods

>>> 'pYtHoN'.swapcase()
'PyThOn'
>>>

Return a copy of the str object with uppercase characters converted to lowercase and vice versa.

Python Syntax

String Methods

>>> a = '\xff\xfe\xfd\xfc\xfb\xfa\xf9\xf8\xf7\xf6\xf5\xf4\xf3\xf2\xf1\xf0\
... \xef\xee\xed\xec\xeb\xea\xe9\xe8\xe7\xe6\xe5\xe4\xe3\xe2\xe1\xe0\
... \xdf\xde\xdd\xdc\xdb\xda\xd9\xd8\xd7\xd6\xd5\xd4\xd3\xd2\xd1\xd0\
... \xcf\xce\xcd\xcc\xcb\xca\xc9\xc8\xc7\xc6\xc5\xc4\xc3\xc2\xc1\xc0\
... \xbf\xbe\xbd\xbc\xbb\xba\xb9\xb8\xb7\xb6\xb5\xb4\xb3\xb2\xb1\xb0\
... \xaf\xae\xad\xac\xab\xaa\xa9\xa8\xa7\xa6\xa5\xa4\xa3\xa2\xa1\xa0\
... \x9f\x9e\x9d\x9c\x9b\x9a\x99\x98\x97\x96\x95\x94\x93\x92\x91\x90\
... \x8f\x8e\x8d\x8c\x8b\x8a\x89\x88\x87\x86\x85\x84\x83\x82\x81\x80\
... \x7f~}|{zyxwvutsrqponmlkjihgfedcba`_^]\\[ZYXWVUTSRQPONMLKJIHGFED\
... CBA@?>=<;:9876543210/.-,+*)(\'&%$#"! \
... \x1f\x1e\x1d\x1c\x1b\x1a\x19\x18\x17\x16\x15\x14\x13\x12\x11\x10\
... \x0f\x0e\r\x0c\x0b\n\t\x08\x07\x06\x05\x04\x03\x02\x01\x00'
>>> 

String Methods

>>> '\x8f\x86\x8b\x97\x90\x91'.translate(a)
'python'
>>> '!+*\x8f\x86\x8b+*!\x97\x90\x91*+!'.translate(a,'+!*')
'python'
>>>

String Methods

>>> 'python'.zfill(20)
'00000000000000python'
>>> 'python python python python'.zfill(20)
'python python python python'
>>>

Sequence Operations

x in sTrue if an element of s is equal to x, else False
x not in sFalse if an element of s is equal to x, else True
s + tthe concatenation of s and t
s * n   or   n * sn shallow copies of s concatenated
s[i](floored) i'th element of s, origin 0
s[i:j]slice of s from i to j
s[i:j:k]slice of s from i to j with step k
len(s)length of s
min(s)smallest element of s
max(s)largest element of s

Sequence Operations

>>> 'h' in 'python'
True
>>> 'yth' in 'python'
True
>>> 'x' in 'python'
False
>>> 

Sequence Operations

>>> 'python' in ['python','zope','plone']
True
>>> 'python' in ['perl','ruby','java']
False
>>> 'python' in ('python','zope','plone')
True
>>> 'python' in ('perl','ruby','java')
False
>>>

Sequence Operations

>>> 'h' not in 'python'
False
>>> 'yth' not in 'python'
False
>>> 'x' not in 'python'
True
>>>

Sequence Operations

>>> 'python' not in ['python','zope','plone']
False
>>> 'python' not in ['perl','ruby','java']
True
>>> 'python' not in ('python','zope','plone')
False
>>> 'python' not in ('perl','ruby','java')
True
>>>

Sequence Operations

>>> 'zope' + '/' + 'plone'
'zope/plone'
>>> ['python','zope','plone'] + ['perl','ruby','java']
['python', 'zope', 'plone', 'perl', 'ruby', 'java']
>>> ('python','zope','plone') + ('perl','ruby','java')
('python', 'zope', 'plone', 'perl', 'ruby', 'java')
>>>

Sequence Operations

>>> 'python' * 3
'pythonpythonpython'
>>> ['python','zope','plone'] * 3
['python', 'zope', 'plone', 'python', 'zope', 'plone',
 'python', 'zope', 'plone']
>>> ('python','zope','plone') * 3
('python', 'zope', 'plone', 'python', 'zope', 'plone',
 'python', 'zope', 'plone')
>>>

Sequence Operations

>>> min('python')
'h'
>>> max('python')
'y'
>>> min('PyThOn')
'O'
>>> max('pYtHoN')
't'
>>>

Sequence Operations

>>> min(['python','zope','plone'])
'plone'
>>> max(['python','zope','plone'])
'zope'
>>> min(['python','zope','plone',min])
<built-in function min>
>>> min(['python','zope','plone',min,3.0])
3.0
>>> min([3,13,23])                    
3
>>> max([3,13,23])
23
>>>

Mapping Types

Dictionaries

>>> dict(((1, 'January'), (2, 'February'), (3, 'March')))
{1: 'January', 2: 'February', 3: 'March'}
>>> a = {4:'April', 5:'May', 6:'June'}
>>> a
{4: 'April', 5: 'May', 6: 'June'}
>>>

Dictionaries

>>> a[5]
'May'
>>> a[5] = 'Beltane'
>>> a
{4: 'April', 5: 'Beltane', 6: 'June'}
>>>

Dictionary Methods

>>> dir({})
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__',
'__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__',
'__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
'__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy',
'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys',
'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>>

Dictionaries have some useful methods.

Dictionary Methods

>>> a
{4: 'April', 5: 'Beltane', 6: 'June'}
>>> a.clear()
>>> a
{}
>>>

Dictionary Methods

>>> a = {1: 'January', 2: 'February', 3: 'March'}
>>> b = a.copy()
>>> b
{1: 'January', 2: 'February', 3: 'March'}
>>> a is b
False
>>> a == b
True
>>>

b is a shallow copy of a.

Dictionary Methods

>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> b
{4: 'April', 5: 'May', 6: 'June'}
>>> a.fromkeys(b, 3.0)
{4: 3.0, 5: 3.0, 6: 3.0}
>>> dict.fromkeys(b, 5L)
{4: 5L, 5: 5L, 6: 5L}
>>>

fromkeys() sets all the values in a new dict object from the keys of another dict object.

Dictionary Methods

>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> a[3]
'March'
>>> a.get(3)
'March'
>>>

get() works almost like the subscription operator.

Dictionary Methods

>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> a[4]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: 4
>>> a.get(4)
>>> a.get(4, 'April')
'April'
>>>

Except that get() avoid raising a KeyError Exception when the key is not found.

Dictionary Methods

>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> a.has_key(3)
True
>>> a.has_key(4)
False
>>>

Dictionary Methods

>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> a.items()
[(1, 'January'), (2, 'February'), (3, 'March')]
>>>

Dictionary Methods

>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> a.keys()
[1, 2, 3]
>>> a.values()
['January', 'February', 'March']
>>> a.items()
[(1, 'January'), (2, 'February'), (3, 'March')]
>>>

Dictionary Methods

>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> a.pop(2)
'February'
>>> a
{1: 'January', 3: 'March'}
>>> a.pop(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: 4
>>> a.pop(4,'April')
'April'
>>>

Dictionary Methods

>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> a.popitem()
(1, 'January')
>>> a
{2: 'February', 3: 'March'}
>>> a.popitem()
(2, 'February')
>>> a.popitem()
(3, 'March')
>>> a.popitem()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: 'popitem(): dictionary is empty'
>>>

Dictionary Methods

>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> b
{4: 'April', 5: 'May', 6: 'June'}
>>> a.update(b)
>>> a
{1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June'}
>>> b
{4: 'April', 5: 'May', 6: 'June'}
>>>

Dictionary Methods

>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> b
{2: 'Imbolc', 4: 'April'}
>>> a.update(b)
>>> a
{1: 'January', 2: 'Imbolc', 3: 'March', 4: 'April'}
>>>

update() overwrites the values of keys which already exist in the target dict object.

Dictionary Methods

>>> a
{1: 'January', 2: 'February', 3: 'March'}
>>> a.setdefault(3,'April')
'March'
>>> a.setdefault(4,'April')
'April'
>>> a
{1: 'January', 2: 'February', 3: 'March', 4: 'April'}
>>>

Dictionary Operations

>>> a
{1: 'January', 2: 'February', 3: 'March', 4: 'April'}
>>> 3 in a
True
>>> 'March' in a
False
>>> 5 in a
False
>>> 5 not in a
True
>>>

Dictionary Operations

>>> a
{1: 'January', 2: 'February', 3: 'March', 4: 'April'}
>>> len(a)
4
>>>

Dictionary Operations

>>> a  
{1: 'January', 2: 'February', 3: 'March', 4: 'April'}
>>> del a[3]
>>> a
{1: 'January', 2: 'February', 4: 'April'}
>>>

String Formatting

>>> format = """%(software)s depends a lot on %(datatype)s.
... I like %(software)s."""
>>> dictionary = {'software':'python', 'datatype':'dictionaries'}
>>> print format % dictionary
python depends a lot on dictionaries.
I like python.
>>>

Set Types

Set Types

>>> set(((6,), 'five', 4+0j, 3.0, 2L, 1))
set([1, 2L, 3.0, (4+0j), 'five', (6,)])
>>> set('python')
set(['h', 'o', 'n', 'p', 't', 'y'])
>>>

Set Types

>>> set(([7], (6,), 'five', 4+0j, 3.0, 2L, 1))
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: list objects are unhashable
>>> set('pythonpython')
set(['h', 'o', 'n', 'p', 't', 'y'])
>>>

Set Types

>>> a = ['eggs','spam','bacon','spam','toast','spam']
>>> a = list(set(a))
>>> a
['toast', 'eggs', 'bacon', 'spam']
>>>

Set and Frozenset Methods

s.issubset(t)test whether every element in s is in t
s.issuperset(t)test whether every element in t is in s
s.union(t)new set with elements from both s and t
s.intersection(t)new set with elements common to s and t
s.difference(t)new set with elements in s but not in t
s.symmetric_difference(t)new set with elements in either s or t but not both
s.copy()new set with a shallow copy of s

Set and Frozenset Operations

len(s)cardinality of set s
x in stest x for membership in s
x not in stest x for non-membership in s
s <= tsame as s.issubset(t)
s >= tsame as s.issuperset(t)
s | tsame as s.union(t)
s & tsame as s.intersection(t)
s - tsame as s.difference(t)
s ^ tsame as s.symmetric_difference(t)

Mutable (Only) Set Methods

s.update(t)update set s, adding elements from t
s.intersection_update(t)update set s, keeping only elements found in both s and t
s.difference_update(t)update set s, removing elements found in t
s.symmetric_difference_update(t)update set s, keeping only elements found in either s or t but not in both
s.add(x)add element x to set s
s.remove(x)remove x from set s; raises KeyError if not present
s.discard(x)removes x from set s if present
s.pop()remove and return an arbitrary element from s; raises KeyError if empty
s.clear()remove all elements from set s

Mutable (Only) Set Operations

s |= tsame as s.update(t)
s &= tsame as s.intersection_update(t)
s -= tsame as s.difference_update(t)
s ^= tsame as s.symmetric_difference_update(t)

Truth Value

That which is not False is True.

What Is False (Equivalent To)?

What Is False (Equivalent To)?

Boolean Logic Python-Style

>>> 123 and 456
456
>>> '' and 456
''
>>> 123 and ''
''
>>> 0 and {}
0
>>>

Boolean Logic Python-Style

>>> 123 or 456
123
>>> '' or 456
456
>>> 123 or ''
123
>>> 0 or {}
{}
>>>

Conditionals

>>> if raw_input() == '456':
...     print "OK"
... else:
...     print "Not OK"
... 
456
OK
>>>

Conditionals

>>> if raw_input() == '456':
...     print "OK"
... else:
...     print "Not OK"
... 
456
OK
>>>

Conditionals

>>> if raw_input() == '456':
...     print "OK"
... else:
...     print "Not OK"
... 
789
Not OK
>>>

Conditionals

Contents of myscript.py:

a = raw_input("Show me the way: ")

if a == '123':
    print 'Up.'
elif a == '456':
    print 'Down.'
else:
    print 'Sorry!'

Conditionals

> python myscript.py
Show me the way: 123
Up.
> python myscript.py
Show me the way: 456
Down.
> python myscript.py
Show me the way: 789
Sorry!
>

Code Blocks

Indefinite Loops

>>> a = 2
>>> while True:
...     a = a**1.01
...     print a
... 

Conditionals

2.01391110011
2.02805952908
   ...
2.31395916722e+303
2.50034103172e+306
Traceback (most recent call last):
  File "<stdin>", line 3, in ?
OverflowError: (34, 'Result too large')
>>>

Indefinite Loops

>>> a = 2
>>> while True:
...     a = a**1.01
...     if a > 100: break
...     print a
... 

Indefinite Loops

2.01391110011
2.02805952908
   ...
94.1911963444
98.5712845404
>>> 

Indefinite Loops

>>> a = 2
>>> while True:
...     a = a**1.01
...     if a > 100: break
...     if a < 50: continue
...     print a
... 

The continue keyword causes the containing loop to skip the remaining statements during the current repitition.

Indefinite Loops

50.1548281185
52.1573927713
   ...
94.1911963444
98.5712845404
>>> 

Indefinite Loops

Contents of myscript.py:

prompt = "Tell me when: "

a = raw_input(prompt)

while a.lower() != "stop":
    b = list(a)
    b.reverse()
    print ''.join(b)
    a = raw_input(prompt)

Indefinite Loops

Contents of myscript.py:

> python myscript.py
Tell me when: python
nohtyp
Tell me when: zope
epoz
Tell me when: Stop
>

The range() Function

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(10,20)
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> range(10,20,2)
[10, 12, 14, 16, 18]
>>> range(20,10,-2)
[20, 18, 16, 14, 12]
>>>

Iterators

Iterators

>>> a = iter('zope')
>>> a.next()
'z'
>>> a.next()
'o'
>>> a.next()
'p'
>>> a.next()
'e'
>>> a.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
StopIteration
>>>

Iterators

>>> a = iter(range(300,0,-100))
>>> a.next()
300
>>> a.next()
200
>>> a.next()
100
>>> a.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
StopIteration
>>>

Definite Loops

>>> for x in range(10):
...     print x**2,
... 
0 1 4 9 16 25 36 49 64 81
>>>

Definite Loops

>>> for x in xrange(10):
...     print x**2,
... 
0 1 4 9 16 25 36 49 64 81
>>>

Definite Loops

>>> breakfast = ['eggs','spam','bacon','spam','toast','spam']
>>> for food in breakfast:
...     print "%s for breakfast!" % food.capitalize()
... 
Eggs for breakfast!
Spam for breakfast!
Bacon for breakfast!
Spam for breakfast!
Toast for breakfast!
Spam for breakfast!
>>>

Definite Loops

>>> dictionary = {'python':'fun','zope':'useful','plone':'teh awesome'}
>>> dictionary.items()
[('python', 'fun'), ('zope', 'useful'), ('plone', 'teh awesome')]
>>> for software, description in dictionary.items():
...     print "%s is %s." % (software.capitalize(), description)
... 
Python is fun.
Zope is useful.
Plone is teh awesome.
>>>

Tuples may unpack directly into a target list of multiple loop control identifiers.

Definite Loops

>>> dictionary = {'python':'fun','zope':'useful','plone':'teh awesome'}
>>> for software, description in dictionary.iteritems():
...     print "%s is %s." % (software.capitalize(), description)
... 
Python is fun.
Zope is useful.
Plone is teh awesome.
>>>

List Comprehensions

>>> [x**2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>>

Equivalent to:

>>> a = []
>>> for x in range(10):
...     a.append(x**2)
... 
>>> a
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>>

Except the list comprehension is an expression.

List Comprehensions

>>> [x**2 for x in range(10) if x%2]
[1, 9, 25, 49, 81]
>>>

Equivalent to:

>>> a = []
>>> for x in range(10):
...     if x%2:
...         a.append(x**2)
... 
>>> a
[1, 9, 25, 49, 81]
>>>

x**2 is called the mapping expression.

List Comprehensions

>>> [x**2 for x in range(10) if x%2]
[1, 9, 25, 49, 81]
>>>

Equivalent to:

>>> a = []
>>> for x in range(10):
...     if x%2:
...         a.append(x**2)
... 
>>> a
[1, 9, 25, 49, 81]
>>>

x%2 is called the filter expression (if present).

List Comprehensions

>>> [x*y for x in xrange(2,8,2) for y in xrange(3,9,3)]
[6, 12, 12, 24, 18, 36]
>>>

Equivalent to:

>>> a = []
>>> for x in xrange(2,8,2):
...     for y in xrange(3,9,3):
...         a.append(x*y)
... 
>>> a
[6, 12, 12, 24, 18, 36]
>>>

Iteration may be nested.

List Comprehensions

>>> [x**y for x in xrange(6) if x%2 for y in xrange(4)]
[1, 1, 1, 1, 1, 3, 9, 27, 1, 5, 25, 125]
>>>

Equivalent to:

>>> a = []
>>> for x in xrange(6):
...     if x%2:
...         for y in xrange(4):
...             a.append(x**y)
... 
>>> a
[1, 1, 1, 1, 1, 3, 9, 27, 1, 5, 25, 125]
>>>

Iteration and filter expressions may be interspersed.

List Comprehensions

>>> [x**y for x in xrange(6) if x%2 for y in xrange(4)]
[1, 1, 1, 1, 1, 3, 9, 27, 1, 5, 25, 125]
>>>

Equivalent to:

>>> a = []
>>> for x in xrange(6):
...     if x%2:
...         for y in xrange(4):
...             a.append(x**y)
... 
>>> a
[1, 1, 1, 1, 1, 3, 9, 27, 1, 5, 25, 125]
>>>

Iteration and filter expressions may be interspersed.

Functions

>>> def f():
...     pass
... 
>>>

Functions

>>> def f(x,a,b,c):
...     print "Executing f(%s,%s,%s,%s)" % (x,a,b,c)
...     return a*x**2 - b*x + c
... 
>>>

Functions

>>> def f(x,a,b,c):
...     print "Executing f(%s,%s,%s,%s)" % (x,a,b,c)
...     return a*x**2 - b*x + c
... 
>>> f(4,3,2,1)
Executing f(4,3,2,1)
41
>>> f(4.5,3.4,2.3,1.2)
Executing f(4.5,3.4,2.3,1.2)
59.699999999999996
>>> f(5+4j,4-3j,3+2j,2-1j)
Executing f((5+4j),(4-3j),(3+2j),(2-1j))
(151+110j)
>>>

Arguments are bound to the identifiers in the parameter list when the function is called.

Functions

>>> def f(x,a,b,c):
...     print "Executing f(%s,%s,%s,%s)" % (x,a,b,c)
...     return a*x**2 - b*x + c
... 
>>> p = f(4,3,2,1)
Executing f(4,3,2,1)
>>> q = f(4.5,3.4,2.3,1.2)
Executing f(4.5,3.4,2.3,1.2)
>>> r = f(5+4j,4-3j,3+2j,2-1j)
Executing f((5+4j),(4-3j),(3+2j),(2-1j))
>>> (p,q,r)
(41, 59.699999999999996, (151+110j))
>>>

Functions

>>> def f(x,a,b,c):
...     print "Executing f(%s,%s,%s,%s)" % (x,a,b,c)
...     return a*x**2 - b*x + c
... 
>>> type(f)
<type 'function'>
>>> g = f
>>> g(1,2,3,4)
Executing f(1,2,3,4)
3
>>>

Functions

>>> def install(application, platform='Linux', clients=1):
...     format = "Installing %s on %s with %s client(s)."
...     print format % (application, platform, clients)
... 
>>>

Parameters may have default values.

Functions

>>> def install(application, platform='Linux', clients=1):
...     format = "Installing %s on %s with %s client(s)."
...     print format % (application, platform, clients)
... 
>>> install('Grok','BSD',3)
Installing Grok on BSD with 3 client(s).
>>> install('Zope',platform='OSX',clients=2)
Installing Zope on OSX with 2 client(s).
>>>

Parameters with default values may have arguments supplied by position or name.

Functions

>>> def install(application, platform='Linux', clients=1):
...     format = "Installing %s on %s with %s client(s)."
...     print format % (application, platform, clients)
... 
>>> install('Zope',platform='OSX')
Installing Zope on OSX with 1 client(s).
>>> install('Zope',clients=2)
Installing Zope on Linux with 2 client(s).
>>> install('Zope')
Installing Zope on Linux with 1 client(s).
>>>

Supplying an argument for a parameter with a default value is optional.

Functions

>>> def install(application, platform='Linux', clients=1):
...     format = "Installing %s on %s with %s client(s)."
...     print format % (application, platform, clients)
... 
>>> install('Plone',clients=4,platform='AIX')
Installing Plone on AIX with 4 client(s).
>>>

Functions

>>> def arglist(a,b,c,*args):
...     print a, b, c,
...     for x in args:
...         print x,
... 
>>> arglist('python','zope','plone','grok','repoze','bfg')
python zope plone grok repoze bfg
>>>

Functions

>>> def kwlist(a,b,c,*args,**kwargs):
...     print a, b, c,
...     for x in args: print x,
...     for k, v in kwargs.items(): print "%s=%s" % (k,v),
... 
>>> kwlist('python','zope','plone',
...        'grok','repoze','bfg',
...        hanno=2305,limi=737,runyaga=730)
python zope plone grok repoze bfg hanno=2305 limi=737 runyaga=730
>>>

Functions

>>>