<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--Converted with LaTeX2HTML 98.2 beta6 (August 14th, 1998)
original version by:  Nikos Drakos, CBLU, University of Leeds
* revised and updated by:  Marcus Hennecke, Ross Moore, Herb Swan
* with significant contributions from:
  Jens Lippmann, Marek Rouchal, Martin Wilck and others -->
<HTML>
<HEAD>
<TITLE>5. Data Structures </TITLE>
<META NAME="description" CONTENT="5. Data Structures ">
<META NAME="keywords" CONTENT="tut">
<META NAME="resource-type" CONTENT="document">
<META NAME="distribution" CONTENT="global">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<LINK REL="STYLESHEET" HREF="tut.css">
<LINK REL="next" HREF="node8.html">
<LINK REL="previous" HREF="node6.html">
<LINK REL="up" HREF="tut.html">
<LINK REL="next" HREF="node8.html">
</HEAD>
<BODY bgcolor="#ffffff">
<div class=navigation>
<table align=center width="100%" cellpadding=0 cellspacing=2>
<tr>
<td><A HREF="node8.html"><img width=32 height=32 align=bottom border=0 alt="next"
 src="../icons/next.gif"></A></td>
<td><A HREF="tut.html"><img width=32 height=32 align=bottom border=0 alt="up"
 src="../icons/up.gif"></A></td>
<td><A HREF="node6.html"><img width=32 height=32 align=bottom border=0 alt="previous"
 src="../icons/previous.gif"></A></td>
<td align=center bgcolor="#99CCFF" width="100%">
 <b class=title>Python Tutorial</b></td>
<td><A HREF="node2.html"><img width=32 height=32 align=bottom border=0 alt="contents"
 src="../icons/contents.gif"></A></td>
<td><img width=32 height=32 align=bottom border=0 alt=""
 src="../icons/blank.gif"></td>
<td><img width=32 height=32 align=bottom border=0 alt=""
 src="../icons/blank.gif"></td>
</tr></table><b class=navlabel>Next:</b> <span class=sectref><A HREF="node8.html">6. Modules</A></span>
<b class=navlabel>Up:</b> <span class=sectref><A HREF="tut.html">Python Tutorial</A></span>
<b class=navlabel>Previous:</b> <span class=sectref><A HREF="node6.html">4. More Control Flow</A></span>
<br><hr></div>
<!--End of Navigation Panel-->
<!--Table of Child-Links-->
<A NAME="CHILD_LINKS"><STRONG>Subsections</STRONG></A>

<UL>
<LI><A NAME="tex2html246"
 HREF="node7.html#SECTION007100000000000000000">5.1 More on Lists </A>
<UL>
<LI><A NAME="tex2html247"
 HREF="node7.html#SECTION007110000000000000000">5.1.1 Functional Programming Tools </A>
</UL>
<LI><A NAME="tex2html248"
 HREF="node7.html#SECTION007200000000000000000">5.2 The <tt class=keyword>del</tt> statement </A>
<LI><A NAME="tex2html249"
 HREF="node7.html#SECTION007300000000000000000">5.3 Tuples and Sequences </A>
<LI><A NAME="tex2html250"
 HREF="node7.html#SECTION007400000000000000000">5.4 Dictionaries </A>
<LI><A NAME="tex2html251"
 HREF="node7.html#SECTION007500000000000000000">5.5 More on Conditions </A>
<LI><A NAME="tex2html252"
 HREF="node7.html#SECTION007600000000000000000">5.6 Comparing Sequences and Other Types </A>
</UL>
<!--End of Table of Child-Links-->
<HR>

<H1><A NAME="SECTION007000000000000000000"></A>
<BR>
5. Data Structures 
</H1>

<P>
This chapter describes some things you've learned about already in
more detail, and adds some new things as well.

<P>

<H1><A NAME="SECTION007100000000000000000"></A>
<BR>
5.1 More on Lists 
</H1>

<P>
The list data type has some more methods.  Here are all of the methods
of list objects:

<P>
<DL>
<DD><P>
<DT><STRONG><tt>insert(i, x)</tt></STRONG>
<DD>Insert an item at a given position.  The first argument is the index of
the element before which to insert, so <tt>a.insert(0, x)</tt> inserts at
the front of the list, and <tt>a.insert(len(a), x)</tt> is equivalent to
<tt>a.append(x)</tt>.

<P>
<DT><STRONG><tt>append(x)</tt></STRONG>
<DD>Equivalent to <tt>a.insert(len(a), x)</tt>.

<P>
<DT><STRONG><tt>index(x)</tt></STRONG>
<DD>Return the index in the list of the first item whose value is <tt>x</tt>.
It is an error if there is no such item.

<P>
<DT><STRONG><tt>remove(x)</tt></STRONG>
<DD>Remove the first item from the list whose value is <tt>x</tt>.
It is an error if there is no such item.

<P>
<DT><STRONG><tt>sort()</tt></STRONG>
<DD>Sort the items of the list, in place.

<P>
<DT><STRONG><tt>reverse()</tt></STRONG>
<DD>Reverse the elements of the list, in place.

<P>
<DT><STRONG><tt>count(x)</tt></STRONG>
<DD>Return the number of times <tt>x</tt> appears in the list.

<P>
</DL>

<P>
An example that uses all list methods:

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; a = [66.6, 333, 333, 1, 1234.5]
&gt;&gt;&gt; print a.count(333), a.count(66.6), a.count('x')
2 1 0
&gt;&gt;&gt; a.insert(2, -1)
&gt;&gt;&gt; a.append(333)
&gt;&gt;&gt; a
[66.6, 333, -1, 333, 1, 1234.5, 333]
&gt;&gt;&gt; a.index(333)
1
&gt;&gt;&gt; a.remove(333)
&gt;&gt;&gt; a
[66.6, -1, 333, 1, 1234.5, 333]
&gt;&gt;&gt; a.reverse()
&gt;&gt;&gt; a
[333, 1234.5, 1, 333, -1, 66.6]
&gt;&gt;&gt; a.sort()
&gt;&gt;&gt; a
[-1, 1, 66.6, 333, 333, 1234.5]
</pre></dl>

<P>

<H2><A NAME="SECTION007110000000000000000"></A>
<BR>
5.1.1 Functional Programming Tools 
</H2>

<P>
There are three built-in functions that are very useful when used with
lists: <tt class=function>filter()</tt>, <tt class=function>map()</tt>, and <tt class=function>reduce()</tt>.

<P>
"<tt class=samp>filter(<var>function</var>, <var>sequence</var>)</tt>" returns a sequence (of
the same type, if possible) consisting of those items from the
sequence for which <tt><var>function</var>(<var>item</var>)</tt> is true.  For
example, to compute some primes:

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; def f(x): return x % 2 != 0 and x % 3 != 0
...
&gt;&gt;&gt; filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
</pre></dl>

<P>
"<tt class=samp>map(<var>function</var>, <var>sequence</var>)</tt>" calls
<tt><var>function</var>(<var>item</var>)</tt> for each of the sequence's items and
returns a list of the return values.  For example, to compute some
cubes:

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; def cube(x): return x*x*x
...
&gt;&gt;&gt; map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
</pre></dl>

<P>
More than one sequence may be passed; the function must then have as
many arguments as there are sequences and is called with the
corresponding item from each sequence (or <tt>None</tt> if some sequence
is shorter than another).  If <tt>None</tt> is passed for the function,
a function returning its argument(s) is substituted.

<P>
Combining these two special cases, we see that
"<tt class=samp>map(None, <var>list1</var>, <var>list2</var>)</tt>" is a convenient way of
turning a pair of lists into a list of pairs.  For example:

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; seq = range(8)
&gt;&gt;&gt; def square(x): return x*x
...
&gt;&gt;&gt; map(None, seq, map(square, seq))
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]
</pre></dl>

<P>
"<tt class=samp>reduce(<var>func</var>, <var>sequence</var>)</tt>" returns a single value
constructed by calling the binary function <var>func</var> on the first two
items of the sequence, then on the result and the next item, and so
on.  For example, to compute the sum of the numbers 1 through 10:

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; def add(x,y): return x+y
...
&gt;&gt;&gt; reduce(add, range(1, 11))
55
</pre></dl>

<P>
If there's only one item in the sequence, its value is returned; if
the sequence is empty, an exception is raised.

<P>
A third argument can be passed to indicate the starting value.  In this
case the starting value is returned for an empty sequence, and the
function is first applied to the starting value and the first sequence
item, then to the result and the next item, and so on.  For example,

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; def sum(seq):
...     def add(x,y): return x+y
...     return reduce(add, seq, 0)
... 
&gt;&gt;&gt; sum(range(1, 11))
55
&gt;&gt;&gt; sum([])
0
</pre></dl>

<P>

<H1><A NAME="SECTION007200000000000000000"></A>
<BR>
5.2 The <tt class=keyword>del</tt> statement 
</H1>

<P>
There is a way to remove an item from a list given its index instead
of its value: the <tt>del</tt> statement.  This can also be used to
remove slices from a list (which we did earlier by assignment of an
empty list to the slice).  For example:

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; a
[-1, 1, 66.6, 333, 333, 1234.5]
&gt;&gt;&gt; del a[0]
&gt;&gt;&gt; a
[1, 66.6, 333, 333, 1234.5]
&gt;&gt;&gt; del a[2:4]
&gt;&gt;&gt; a
[1, 66.6, 1234.5]
</pre></dl>

<P>
<tt class=keyword>del</tt> can also be used to delete entire variables:

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; del a
</pre></dl>

<P>
Referencing the name <tt>a</tt> hereafter is an error (at least until
another value is assigned to it).  We'll find other uses for
<tt class=keyword>del</tt> later.

<P>

<H1><A NAME="SECTION007300000000000000000"></A>
<BR>
5.3 Tuples and Sequences 
</H1>

<P>
We saw that lists and strings have many common properties, e.g.,
indexing and slicing operations.  They are two examples of
<i>sequence</i> data types.  Since Python is an evolving language,
other sequence data types may be added.  There is also another
standard sequence data type: the <i>tuple</i>.

<P>
A tuple consists of a number of values separated by commas, for
instance:

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; t = 12345, 54321, 'hello!'
&gt;&gt;&gt; t[0]
12345
&gt;&gt;&gt; t
(12345, 54321, 'hello!')
&gt;&gt;&gt; # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
&gt;&gt;&gt; u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
</pre></dl>

<P>
As you see, on output tuples are alway enclosed in parentheses, so
that nested tuples are interpreted correctly; they may be input with
or without surrounding parentheses, although often parentheses are
necessary anyway (if the tuple is part of a larger expression).

<P>
Tuples have many uses, e.g., (x, y) coordinate pairs, employee records
from a database, etc.  Tuples, like strings, are immutable: it is not
possible to assign to the individual items of a tuple (you can
simulate much of the same effect with slicing and concatenation,
though).

<P>
A special problem is the construction of tuples containing 0 or 1
items: the syntax has some extra quirks to accommodate these.  Empty
tuples are constructed by an empty pair of parentheses; a tuple with
one item is constructed by following a value with a comma
(it is not sufficient to enclose a single value in parentheses).
Ugly, but effective.  For example:

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; empty = ()
&gt;&gt;&gt; singleton = 'hello',    # &lt;-- note trailing comma
&gt;&gt;&gt; len(empty)
0
&gt;&gt;&gt; len(singleton)
1
&gt;&gt;&gt; singleton
('hello',)
</pre></dl>

<P>
The statement <tt>t = 12345, 54321, 'hello!'</tt> is an example of
<i>tuple packing</i>: the values <tt>12345</tt>, <tt>54321</tt> and
<tt>'hello!'</tt> are packed together in a tuple.  The reverse operation
is also possible, e.g.:

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; x, y, z = t
</pre></dl>

<P>
This is called, appropriately enough, <i>tuple unpacking</i>.  Tuple
unpacking requires that the list of variables on the left has the same
number of elements as the length of the tuple.  Note that multiple
assignment is really just a combination of tuple packing and tuple
unpacking!

<P>
Occasionally, the corresponding operation on lists is useful: <i>list
unpacking</i>.  This is supported by enclosing the list of variables in
square brackets:

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; a = ['spam', 'eggs', 100, 1234]
&gt;&gt;&gt; [a1, a2, a3, a4] = a
</pre></dl>

<P>

<H1><A NAME="SECTION007400000000000000000"></A>
<BR>
5.4 Dictionaries 
</H1>

<P>
Another useful data type built into Python is the <i>dictionary</i>.
Dictionaries are sometimes found in other languages as ``associative
memories'' or ``associative arrays''.  Unlike sequences, which are
indexed by a range of numbers, dictionaries are indexed by <i>keys</i>,
which can be any non-mutable type; strings and numbers can always be
keys.  Tuples can be used as keys if they contain only strings,
numbers, or tuples.  You can't use lists as keys, since lists can be
modified in place using their <tt>append()</tt> method.

<P>
It is best to think of a dictionary as an unordered set of
<i>key:value</i> pairs, with the requirement that the keys are unique
(within one dictionary).
A pair of braces creates an empty dictionary: <tt>{}</tt>.
Placing a comma-separated list of key:value pairs within the
braces adds initial key:value pairs to the dictionary; this is also the
way dictionaries are written on output.

<P>
The main operations on a dictionary are storing a value with some key
and extracting the value given the key.  It is also possible to delete
a key:value pair
with <tt>del</tt>.
If you store using a key that is already in use, the old value
associated with that key is forgotten.  It is an error to extract a
value using a non-existent key.

<P>
The <tt>keys()</tt> method of a dictionary object returns a list of all the
keys used in the dictionary, in random order (if you want it sorted,
just apply the <tt>sort()</tt> method to the list of keys).  To check
whether a single key is in the dictionary, use the <tt>has_key()</tt>method of the dictionary.

<P>
Here is a small example using a dictionary:

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; tel = {'jack': 4098, 'sape': 4139}
&gt;&gt;&gt; tel['guido'] = 4127
&gt;&gt;&gt; tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}
&gt;&gt;&gt; tel['jack']
4098
&gt;&gt;&gt; del tel['sape']
&gt;&gt;&gt; tel['irv'] = 4127
&gt;&gt;&gt; tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
&gt;&gt;&gt; tel.keys()
['guido', 'irv', 'jack']
&gt;&gt;&gt; tel.has_key('guido')
1
</pre></dl>

<P>

<H1><A NAME="SECTION007500000000000000000"></A>
<BR>
5.5 More on Conditions 
</H1>

<P>
The conditions used in <tt>while</tt> and <tt>if</tt> statements above can
contain other operators besides comparisons.

<P>
The comparison operators <tt>in</tt> and <tt>not in</tt> check whether a value
occurs (does not occur) in a sequence.  The operators <tt>is</tt> and
<tt>is not</tt> compare whether two objects are really the same object; this
only matters for mutable objects like lists.  All comparison operators
have the same priority, which is lower than that of all numerical
operators.

<P>
Comparisons can be chained: e.g., <tt>a &lt; b == c</tt> tests whether <tt>a</tt>is less than <tt>b</tt> and moreover <tt>b</tt> equals <tt>c</tt>.

<P>
Comparisons may be combined by the Boolean operators <tt>and</tt> and
<tt>or</tt>, and the outcome of a comparison (or of any other Boolean
expression) may be negated with <tt>not</tt>.  These all have lower
priorities than comparison operators again; between them, <tt>not</tt> has
the highest priority, and <tt>or</tt> the lowest, so that
<tt>A and not B or C</tt> is equivalent to <tt>(A and (not B)) or C</tt>.  Of
course, parentheses can be used to express the desired composition.

<P>
The Boolean operators <tt>and</tt> and <tt>or</tt> are so-called
<i>shortcut</i> operators: their arguments are evaluated from left to
right, and evaluation stops as soon as the outcome is determined.
E.g., if <tt>A</tt> and <tt>C</tt> are true but <tt>B</tt> is false, <tt>A
and B and C</tt> does not evaluate the expression C.  In general, the
return value of a shortcut operator, when used as a general value and
not as a Boolean, is the last evaluated argument.

<P>
It is possible to assign the result of a comparison or other Boolean
expression to a variable.  For example,

<P>
<dl><dd><pre class=verbatim>
&gt;&gt;&gt; string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
&gt;&gt;&gt; non_null = string1 or string2 or string3
&gt;&gt;&gt; non_null
'Trondheim'
</pre></dl>

<P>
Note that in Python, unlike C, assignment cannot occur inside expressions.

<P>

<H1><A NAME="SECTION007600000000000000000"></A>
<BR>
5.6 Comparing Sequences and Other Types 
</H1>

<P>
Sequence objects may be compared to other objects with the same
sequence type.  The comparison uses <i>lexicographical</i> ordering:
first the first two items are compared, and if they differ this
determines the outcome of the comparison; if they are equal, the next
two items are compared, and so on, until either sequence is exhausted.
If two items to be compared are themselves sequences of the same type,
the lexicographical comparison is carried out recursively.  If all
items of two sequences compare equal, the sequences are considered
equal.  If one sequence is an initial subsequence of the other, the
shorted sequence is the smaller one.  Lexicographical ordering for
strings uses the ASCII ordering for individual characters.  Some
examples of comparisons between sequences with the same types:

<P>
<dl><dd><pre class=verbatim>
(1, 2, 3)              &lt; (1, 2, 4)
[1, 2, 3]              &lt; [1, 2, 4]
'ABC' &lt; 'C' &lt; 'Pascal' &lt; 'Python'
(1, 2, 3, 4)           &lt; (1, 2, 4)
(1, 2)                 &lt; (1, 2, -1)
(1, 2, 3)             == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab'))   &lt; (1, 2, ('abc', 'a'), 4)
</pre></dl>

<P>
Note that comparing objects of different types is legal.  The outcome
is deterministic but arbitrary: the types are ordered by their name.
Thus, a list is always smaller than a string, a string is always
smaller than a tuple, etc.  Mixed numeric types are compared according
to their numeric value, so 0 equals 0.0, etc.<A NAME="tex2html3"
 HREF="#foot516"><SUP>5.1</SUP></A>
<P>
<BR><HR><H4>Footnotes</H4>
<DL>
<DT><A NAME="foot516">... etc.</A><A NAME="foot516"
 HREF="node7.html#tex2html3"><SUP>5.1</SUP></A>
<DD>
        The rules for comparing objects of different types should
        not be relied upon; they may change in a future version of
        the language.


</DL><p>
<div class=navigation><hr><table align=center width="100%" cellpadding=0 cellspacing=2>
<tr>
<td><A HREF="node8.html"><img width=32 height=32 align=bottom border=0 alt="next"
 src="../icons/next.gif"></A></td>
<td><A HREF="tut.html"><img width=32 height=32 align=bottom border=0 alt="up"
 src="../icons/up.gif"></A></td>
<td><A HREF="node6.html"><img width=32 height=32 align=bottom border=0 alt="previous"
 src="../icons/previous.gif"></A></td>
<td align=center bgcolor="#99CCFF" width="100%">
 <b class=title>Python Tutorial</b></td>
<td><A HREF="node2.html"><img width=32 height=32 align=bottom border=0 alt="contents"
 src="../icons/contents.gif"></A></td>
<td><img width=32 height=32 align=bottom border=0 alt=""
 src="../icons/blank.gif"></td>
<td><img width=32 height=32 align=bottom border=0 alt=""
 src="../icons/blank.gif"></td>
</tr></table><b class=navlabel>Next:</b> <span class=sectref><A HREF="node8.html">6. Modules</A></span>
<b class=navlabel>Up:</b> <span class=sectref><A HREF="tut.html">Python Tutorial</A></span>
<b class=navlabel>Previous:</b> <span class=sectref><A HREF="node6.html">4. More Control Flow</A></span>
</div>
<!--End of Navigation Panel-->
<ADDRESS>
<hr>Send comments on this document to <a href="mailto:python-docs@python.org">python-docs@python.org</a>.
</ADDRESS>
</BODY>
</HTML>
