% python
>>> len([1, 2, 3])                    # Length
3
>>> [1, 2, 3] + [4, 5, 6]             # Concatenation
[1, 2, 3, 4, 5, 6]
>>> ['Ni!'] * 4                       # Repetition
['Ni!', 'Ni!', 'Ni!', 'Ni!']
>>> 3 in [1, 2, 3]                    # Membership
True
>>> for x in [1, 2, 3]: print x,      # Iteration
...
1 2 3



>>> str([1, 2]) + "34"           # Same as "[1, 2]" + "34"
'[1, 2]34'
>>> [1, 2] + list("34")          # Same as [1, 2] + ["3", "4"]
[1, 2, '3', '4']



>>> L = ['spam', 'Spam', 'SPAM!']
>>> L[2]                               # Offsets start at zero.
'SPAM!'
>>> L[-2]                              # Negative: count from the right.
'Spam'
>>> L[1:]                              # Slicing fetches sections.
['Spam', 'SPAM!']



>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> matrix[1]
[4, 5, 6]
>>> matrix[1][1]
5
>>> matrix[2][0]
7 
>>> matrix = [[1, 2, 3],
...           [4, 5, 6],
...           [7, 8, 9]]
>>> matrix[1][1]
5



>>> L = ['spam', 'Spam', 'SPAM!']
>>> L[1] = 'eggs'                  # Index assignment
>>> L
['spam', 'eggs', 'SPAM!']
>>> L[0:2] = ['eat', 'more']       # Slice assignment: delete+insert
>>> L                              # Replaces items 0,1
['eat', 'more', 'SPAM!']



>>> L.append('please')                # Append method call.
>>> L
['eat', 'more', 'SPAM!', 'please']
>>> L.sort()                          # Sort list items ('S' < 'e').
>>> L
['SPAM!', 'eat', 'more', 'please']



>>> L = [1, 2]
>>> L.extend([3,4,5])      # Append multiple items.
>>> L
[1, 2, 3, 4, 5]
>>> L.pop()                # Delete, return last item.
5
>>> L
[1, 2, 3, 4]
>>> L.reverse()            # In-place reversal.
>>> L
[4, 3, 2, 1]



>>> L = []
>>> L.append(1)                    # Push onto stack.
>>> L.append(2)
>>> L
[1, 2]
>>> L.pop()                        # Pop off stack.
2
>>> L
[1]



>>> L
['SPAM!', 'eat', 'more', 'please']
>>> del L[0]                       # Delete one item.
>>> L
['eat', 'more', 'please']
>>> del L[1:]                      # Delete an entire section.
>>> L                              # Same as L[1:] = []
['eat']



>>> L = ['Already', 'got', 'one']
>>> L[1:] = []
>>> L
['Already']
>>> L[0] = []
>>> L
[[]]





% python
>>> d2 = {'spam': 2, 'ham': 1, 'eggs': 3}    # Make a dictionary.
>>> d2['spam']                               # Fetch value by key.
2
>>> d2                                       # Order is scrambled.
{'eggs': 3, 'ham': 1, 'spam': 2}



>>> len(d2)                    # Number of entries in dictionary
3
>>> d2.has_key('ham')          # Key membership test
True
>>> 'ham' in d2                # Key membership test alternative
True
>>> d2.keys()                  # Create a new list of my keys.
['eggs', 'ham', 'spam']



>>> d2['ham'] = ['grill', 'bake', 'fry']      # Change entry.
>>> d2
{'eggs': 3, 'spam': 2, 'ham': ['grill', 'bake', 'fry']}

>>> del d2['eggs']                            # Delete entry.
>>> d2
{'spam': 2, 'ham': ['grill', 'bake', 'fry']}

>>> d2['brunch'] = 'Bacon'                    # Add new entry.
>>> d2
{'brunch': 'Bacon', 'spam': 2, 'ham': ['grill', 'bake', 'fry']}



>>> d2 = {'spam': 2, 'ham': 1, 'eggs': 3}
>>> d2.values()
 [3, 1, 2] 
>>> d2.items()
 [('eggs', 3), ('ham', 1), ('spam', 2)]



>>> d2.get('spam')                  # a key that is there
2
>>> d2.get('toast')                 # a key that is missing
None
>>> d2.get('toast', 88)
88



>>> d2
{'eggs': 3, 'ham': 1, 'spam': 2}
>>> d3 = {'toast':4, 'muffin':5}
>>> d2.update(d3)
>>> d2
{'toast': 4, 'muffin': 5, 'eggs': 3, 'ham': 1, 'spam': 2}



# pop a dictionary by key

>>> d2
{'toast': 4, 'muffin': 5, 'eggs': 3, 'ham': 1, 'spam': 2}
>>> d2.pop('muffin')
5
>>> d2.pop('toast')                         # delete and return from a key
4
>>> d2
{'eggs': 3, 'ham': 1, 'spam': 2}

# pop a list by position

>>> L = ['aa', 'bb', 'cc', 'dd']
>>> L.pop()                                 # delete and return from the end
'dd'
>>> L
['aa', 'bb', 'cc']
>>> L.pop(1)                                # delete from a specific position
'bb'
>>> L
['aa', 'cc']



>>> table = {'Python':  'Guido van Rossum',
...          'Perl':    'Larry Wall',
...          'Tcl':     'John Ousterhout' }
...
>>> language = 'Python'
>>> creator  = table[language]
>>> creator
'Guido van Rossum'

>>> for lang in table.keys(): 
...     print lang, '\t', table[lang]
...
Tcl     John Ousterhout
Python  Guido van Rossum
Perl    Larry Wall



>>> L = []
>>> L[99] = 'spam'
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IndexError: list assignment index out of range



>>> D = {}
>>> D[99] = 'spam'
>>> D[99]
'spam'
>>> D
{99: 'spam'}



>>> Matrix = {}
>>> Matrix[(2, 3, 4)] = 88
>>> Matrix[(7, 8, 9)] = 99
>>>
>>> X = 2; Y = 3; Z = 4              # ; separates statements.
>>> Matrix[(X, Y, Z)]
88
>>> Matrix
{(2, 3, 4): 88, (7, 8, 9): 99}



>>> Matrix[(2,3,6)]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: (2, 3, 6)



>>> if Matrix.has_key((2,3,6)):     # Check for key before fetch.
...     print Matrix[(2,3,6)]
... else:
...     print 0
...
0
>>> try:
...     print Matrix[(2,3,6)]       # Try to index.
... except KeyError:                # Catch and recover.
...     print 0
...
0 
>>> Matrix.get((2,3,4), 0)          # Exists; fetch and return.
88 
>>> Matrix.get((2,3,6), 0)          # Doesn't exist; use default arg.
0



>>> rec = {}
>>> rec['name'] = 'mel'
>>> rec['age']  = 45
>>> rec['job']  = 'trainer/writer'
>>>
>>> print rec['name']
mel



>>> mel = {'name': 'Mark',
...        'jobs': ['trainer', 'writer'],
...        'web':  'www.rmi.net/~lutz',
...        'home': {'state': 'CO', 'zip':80513}}



>>> mel['name']
'Mark'
>>> mel['jobs']
['trainer', 'writer']
>>> mel['jobs'][1]
'writer'
>>> mel['home']['zip']
80513



{'name': 'mel', 'age': 45}             # traditional literal expression

D = {}                                 # assign by keys dynamically
D['name'] = 'mel'
D['age']  = 45

dict(name='mel', age=45)               # keyword argument form

dict([('name', 'mel'), ('age', 45)])   # key/value tuples form



>>> dict.fromkeys(['a', 'b'], 0)
{'a': 0, 'b': 0}



import anydbm
file = anydbm.open("filename") # Link to file.
file['key'] = 'data'           # Store data by key.
data = file['key']             # Fetch data by key.



import cgi
form = cgi.FieldStorage()    # Parse form data.
if form.has_key('name'):
    showReply('Hello, ' + form['name'].value)

