Advanced Data Types

More about lists

Lists can be 'sliced' using indexing and the colon.
This produces a sub-list.

>>> l = [1, 2, 3, 4, 5, 6, 7]
>>> l[1:2]
[2]
>>> l[3:6]
[4, 5, 6]
>>> l[2:]
[3, 4, 5, 6, 7]

Slicing can also be applied to strings.

Other functions that exist for lists are: append, sort, reverse, and index.

>>> l2 = [3, 7, 2]
>>> l2.append(1)
>>> l2
[3, 7, 2, 1]

>>> l2.sort()
>>> l2
[1, 2, 3, 7]

>>> l2.reverse()
>>> l2
[7, 3, 2, 1]

>>> l2.index(3)
1
>>> l2.index(4)
Traceback (most recent call last):
  File "", line 1, in ?
ValueError: list.index(x): x not in list

The global function len will return the number of items in a list.

>>> len([1, 2, 3])
3
>>> len([1, 2, [3, 4]])
3








Tuples

A tuple is very similar to a list, except that it is immutable - its contents can't be changed once created.

Tuple literals are defined in parentheses, rather than square brackets, or just as a series of comma-separated values with nothing around them.

>>> x = (1, 2, 3)
>>> z = 1,2
>>> z
(1, 2)

A major use for tuples is to provide multiple return values from a function.

>>> def doubledouble(x,y):
...     return x*2, y*2
...
>>> a,b = doubledouble(3,5)
>>> print a
6
>>> print b
10








Dictionaries

A dictionary is similar to a list, except that you can index it by any value, rather than just the numbers 0 to N-1.

Another term for a dictionary is an "associative array" - it associates values with keys.

>>> primitive = { 'point' : 1,     'line' : 2,     'triangle' : 3 }
>>> primitive['line']
2

A dictionary consists of keys and values. These can be retrieved via the functions keys and values.

>>> primitive.keys()
['line', 'triangle', 'point']
>>> primitive.values()
[2, 3, 1]

The function has_key is useful to find out if a particular key exists in a dictionary, before trying to use it.

>>> primitive['square']
Traceback (most recent call last):
  File "", line 1, in ?
KeyError: square
>>> if primitive.has_key('square'):
...     print primitive['square']
... else:
...     print 'no such key'
...
no such key










next