Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / v9 / html / python / tut / node7.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<link rel="STYLESHEET" href="tut.css" type='text/css' />
<link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" />
<link rel='start' href='../index.html' title='Python Documentation Index' />
<link rel="first" href="tut.html" title='Python Tutorial' />
<link rel='contents' href='node2.html' title="Contents" />
<link rel='index' href='node19.html' title='Index' />
<link rel='last' href='about.html' title='About this document...' />
<link rel='help' href='about.html' title='About this document...' />
<link rel="next" href="node8.html" />
<link rel="prev" href="node6.html" />
<link rel="parent" href="tut.html" />
<link rel="next" href="node8.html" />
<meta name='aesop' content='information' />
<title>5. Data Structures </title>
</head>
<body>
<DIV CLASS="navigation">
<div id='top-navigation-panel' xml:id='top-navigation-panel'>
<table align="center" width="100%" cellpadding="0" cellspacing="2">
<tr>
<td class='online-navigation'><a rel="prev" title="4. More Control Flow"
href="node6.html"><img src='../icons/previous.png'
border='0' height='32' alt='Previous Page' width='32' /></A></td>
<td class='online-navigation'><a rel="parent" title="Python Tutorial"
href="tut.html"><img src='../icons/up.png'
border='0' height='32' alt='Up One Level' width='32' /></A></td>
<td class='online-navigation'><a rel="next" title="6. Modules"
href="node8.html"><img src='../icons/next.png'
border='0' height='32' alt='Next Page' width='32' /></A></td>
<td align="center" width="100%">Python Tutorial</td>
<td class='online-navigation'><a rel="contents" title="Table of Contents"
href="node2.html"><img src='../icons/contents.png'
border='0' height='32' alt='Contents' width='32' /></A></td>
<td class='online-navigation'><img src='../icons/blank.png'
border='0' height='32' alt='' width='32' /></td>
<td class='online-navigation'><a rel="index" title="Index"
href="node19.html"><img src='../icons/index.png'
border='0' height='32' alt='Index' width='32' /></A></td>
</tr></table>
<div class='online-navigation'>
<b class="navlabel">Previous:</b>
<a class="sectref" rel="prev" href="node6.html">4. More Control Flow</A>
<b class="navlabel">Up:</b>
<a class="sectref" rel="parent" href="tut.html">Python Tutorial</A>
<b class="navlabel">Next:</b>
<a class="sectref" rel="next" href="node8.html">6. Modules</A>
</div>
<hr /></div>
</DIV>
<!--End of Navigation Panel-->
<div class='online-navigation'>
<!--Table of Child-Links-->
<A NAME="CHILD_LINKS"><STRONG>Subsections</STRONG></a>
<UL CLASS="ChildLinks">
<LI><A href="node7.html#SECTION007100000000000000000">5.1 More on Lists</a>
<UL>
<LI><A href="node7.html#SECTION007110000000000000000">5.1.1 Using Lists as Stacks</a>
<LI><A href="node7.html#SECTION007120000000000000000">5.1.2 Using Lists as Queues</a>
<LI><A href="node7.html#SECTION007130000000000000000">5.1.3 Functional Programming Tools</a>
<LI><A href="node7.html#SECTION007140000000000000000">5.1.4 List Comprehensions</a>
</ul>
<LI><A href="node7.html#SECTION007200000000000000000">5.2 The <tt class="keyword">del</tt> statement</a>
<LI><A href="node7.html#SECTION007300000000000000000">5.3 Tuples and Sequences</a>
<LI><A href="node7.html#SECTION007400000000000000000">5.4 Sets</a>
<LI><A href="node7.html#SECTION007500000000000000000">5.5 Dictionaries</a>
<LI><A href="node7.html#SECTION007600000000000000000">5.6 Looping Techniques</a>
<LI><A href="node7.html#SECTION007700000000000000000">5.7 More on Conditions</a>
<LI><A href="node7.html#SECTION007800000000000000000">5.8 Comparing Sequences and Other Types</a>
</ul>
<!--End of Table of Child-Links-->
</div>
<HR>
<H1><A NAME="SECTION007000000000000000000"></A><A NAME="structures"></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><A NAME="moreLists"></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><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
<td><nobr><b><tt id='l2h-9' xml:id='l2h-9' class="method">append</tt></b>(</nobr></td>
<td><var>x</var>)</td></tr></table></dt>
<dd>
Add an item to the end of the list;
equivalent to <code>a[len(a):] = [<var>x</var>]</code>.
</dl>
<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
<td><nobr><b><tt id='l2h-10' xml:id='l2h-10' class="method">extend</tt></b>(</nobr></td>
<td><var>L</var>)</td></tr></table></dt>
<dd>
Extend the list by appending all the items in the given list;
equivalent to <code>a[len(a):] = <var>L</var></code>.
</dl>
<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
<td><nobr><b><tt id='l2h-11' xml:id='l2h-11' class="method">insert</tt></b>(</nobr></td>
<td><var>i, x</var>)</td></tr></table></dt>
<dd>
Insert an item at a given position. The first argument is the index
of the element before which to insert, so <code>a.insert(0, <var>x</var>)</code>
inserts at the front of the list, and <code>a.insert(len(a), <var>x</var>)</code>
is equivalent to <code>a.append(<var>x</var>)</code>.
</dl>
<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
<td><nobr><b><tt id='l2h-12' xml:id='l2h-12' class="method">remove</tt></b>(</nobr></td>
<td><var>x</var>)</td></tr></table></dt>
<dd>
Remove the first item from the list whose value is <var>x</var>.
It is an error if there is no such item.
</dl>
<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
<td><nobr><b><tt id='l2h-13' xml:id='l2h-13' class="method">pop</tt></b>(</nobr></td>
<td><var></var><big>[</big><var>i</var><big>]</big><var></var>)</td></tr></table></dt>
<dd>
Remove the item at the given position in the list, and return it. If
no index is specified, <code>a.pop()</code> removes and returns the last item
in the list. The item is also removed from the list. (The square brackets
around the <var>i</var> in the method signature denote that the parameter
is optional, not that you should type square brackets at that
position. You will see this notation frequently in the
<em class="citetitle"><a
href="../lib/lib.html"
title="Python Library Reference"
>Python Library Reference</a></em>.)
</dl>
<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
<td><nobr><b><tt id='l2h-14' xml:id='l2h-14' class="method">index</tt></b>(</nobr></td>
<td><var>x</var>)</td></tr></table></dt>
<dd>
Return the index in the list of the first item whose value is <var>x</var>.
It is an error if there is no such item.
</dl>
<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
<td><nobr><b><tt id='l2h-15' xml:id='l2h-15' class="method">count</tt></b>(</nobr></td>
<td><var>x</var>)</td></tr></table></dt>
<dd>
Return the number of times <var>x</var> appears in the list.
</dl>
<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
<td><nobr><b><tt id='l2h-16' xml:id='l2h-16' class="method">sort</tt></b>(</nobr></td>
<td><var></var>)</td></tr></table></dt>
<dd>
Sort the items of the list, in place.
</dl>
<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
<td><nobr><b><tt id='l2h-17' xml:id='l2h-17' class="method">reverse</tt></b>(</nobr></td>
<td><var></var>)</td></tr></table></dt>
<dd>
Reverse the elements of the list, in place.
</dl>
<P>
An example that uses most of the list methods:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; a = [66.25, 333, 333, 1, 1234.5]
&gt;&gt;&gt; print a.count(333), a.count(66.25), a.count('x')
2 1 0
&gt;&gt;&gt; a.insert(2, -1)
&gt;&gt;&gt; a.append(333)
&gt;&gt;&gt; a
[66.25, 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.25, -1, 333, 1, 1234.5, 333]
&gt;&gt;&gt; a.reverse()
&gt;&gt;&gt; a
[333, 1234.5, 1, 333, -1, 66.25]
&gt;&gt;&gt; a.sort()
&gt;&gt;&gt; a
[-1, 1, 66.25, 333, 333, 1234.5]
</pre></div>
<P>
<H2><A NAME="SECTION007110000000000000000"></A><A NAME="lists-as-stacks"></A>
<BR>
5.1.1 Using Lists as Stacks
</H2>
<P>
The list methods make it very easy to use a list as a stack, where the
last element added is the first element retrieved (``last-in,
first-out''). To add an item to the top of the stack, use
<tt class="method">append()</tt>. To retrieve an item from the top of the stack, use
<tt class="method">pop()</tt> without an explicit index. For example:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; stack = [3, 4, 5]
&gt;&gt;&gt; stack.append(6)
&gt;&gt;&gt; stack.append(7)
&gt;&gt;&gt; stack
[3, 4, 5, 6, 7]
&gt;&gt;&gt; stack.pop()
7
&gt;&gt;&gt; stack
[3, 4, 5, 6]
&gt;&gt;&gt; stack.pop()
6
&gt;&gt;&gt; stack.pop()
5
&gt;&gt;&gt; stack
[3, 4]
</pre></div>
<P>
<H2><A NAME="SECTION007120000000000000000"></A><A NAME="lists-as-queues"></A>
<BR>
5.1.2 Using Lists as Queues
</H2>
<P>
You can also use a list conveniently as a queue, where the first
element added is the first element retrieved (``first-in,
first-out''). To add an item to the back of the queue, use
<tt class="method">append()</tt>. To retrieve an item from the front of the queue,
use <tt class="method">pop()</tt> with <code>0</code> as the index. For example:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; queue = ["Eric", "John", "Michael"]
&gt;&gt;&gt; queue.append("Terry") # Terry arrives
&gt;&gt;&gt; queue.append("Graham") # Graham arrives
&gt;&gt;&gt; queue.pop(0)
'Eric'
&gt;&gt;&gt; queue.pop(0)
'John'
&gt;&gt;&gt; queue
['Michael', 'Terry', 'Graham']
</pre></div>
<P>
<H2><A NAME="SECTION007130000000000000000"></A><A NAME="functional"></A>
<BR>
5.1.3 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
consisting of those items from the
sequence for which <code><var>function</var>(<var>item</var>)</code> is true.
If <var>sequence</var> is a <tt class="class">string</tt> or <tt class="class">tuple</tt>, the result will
be of the same type; otherwise, it is always a <tt class="class">list</tt>.
For example, to compute some primes:
<P>
<div class="verbatim"><pre>
&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></div>
<P>
"<tt class="samp">map(<var>function</var>, <var>sequence</var>)</tt>" calls
<code><var>function</var>(<var>item</var>)</code> for each of the sequence's items and
returns a list of the return values. For example, to compute some
cubes:
<P>
<div class="verbatim"><pre>
&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></div>
<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 <code>None</code> if some sequence
is shorter than another). For example:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; seq = range(8)
&gt;&gt;&gt; def add(x, y): return x+y
...
&gt;&gt;&gt; map(add, seq, seq)
[0, 2, 4, 6, 8, 10, 12, 14]
</pre></div>
<P>
"<tt class="samp">reduce(<var>function</var>, <var>sequence</var>)</tt>" returns a single value
constructed by calling the binary function <var>function</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>
<div class="verbatim"><pre>
&gt;&gt;&gt; def add(x,y): return x+y
...
&gt;&gt;&gt; reduce(add, range(1, 11))
55
</pre></div>
<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>
<div class="verbatim"><pre>
&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></div>
<P>
Don't use this example's definition of <tt class="function">sum()</tt>: since summing
numbers is such a common need, a built-in function
<code>sum(<var>sequence</var>)</code> is already provided, and works exactly like
this.
<span class="versionnote">New in version 2.3.</span>
<P>
<H2><A NAME="SECTION007140000000000000000">
5.1.4 List Comprehensions</A>
</H2>
<P>
List comprehensions provide a concise way to create lists without resorting
to use of <tt class="function">map()</tt>, <tt class="function">filter()</tt> and/or <tt class="keyword">lambda</tt>.
The resulting list definition tends often to be clearer than lists built
using those constructs. Each list comprehension consists of an expression
followed by a <tt class="keyword">for</tt> clause, then zero or more <tt class="keyword">for</tt> or
<tt class="keyword">if</tt> clauses. The result will be a list resulting from evaluating
the expression in the context of the <tt class="keyword">for</tt> and <tt class="keyword">if</tt> clauses
which follow it. If the expression would evaluate to a tuple, it must be
parenthesized.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; freshfruit = [' banana', ' loganberry ', 'passion fruit ']
&gt;&gt;&gt; [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
&gt;&gt;&gt; vec = [2, 4, 6]
&gt;&gt;&gt; [3*x for x in vec]
[6, 12, 18]
&gt;&gt;&gt; [3*x for x in vec if x &gt; 3]
[12, 18]
&gt;&gt;&gt; [3*x for x in vec if x &lt; 2]
[]
&gt;&gt;&gt; [[x,x**2] for x in vec]
[[2, 4], [4, 16], [6, 36]]
&gt;&gt;&gt; [x, x**2 for x in vec] # error - parens required for tuples
File "&lt;stdin&gt;", line 1, in ?
[x, x**2 for x in vec]
^
SyntaxError: invalid syntax
&gt;&gt;&gt; [(x, x**2) for x in vec]
[(2, 4), (4, 16), (6, 36)]
&gt;&gt;&gt; vec1 = [2, 4, 6]
&gt;&gt;&gt; vec2 = [4, 3, -9]
&gt;&gt;&gt; [x*y for x in vec1 for y in vec2]
[8, 6, -18, 16, 12, -36, 24, 18, -54]
&gt;&gt;&gt; [x+y for x in vec1 for y in vec2]
[6, 5, -7, 8, 7, -5, 10, 9, -3]
&gt;&gt;&gt; [vec1[i]*vec2[i] for i in range(len(vec1))]
[8, 12, -54]
</pre></div>
<P>
List comprehensions are much more flexible than <tt class="function">map()</tt> and can be
applied to complex expressions and nested functions:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; [str(round(355/113.0, i)) for i in range(1,6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']
</pre></div>
<P>
<H1><A NAME="SECTION007200000000000000000"></A><A NAME="del"></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 class="keyword">del</tt> statement. Unlike the <tt class="method">pop()</tt>)
method which returns a value, the <tt class="keyword">del</tt> keyword is a statement
and 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>
<div class="verbatim"><pre>
&gt;&gt;&gt; a = [-1, 1, 66.25, 333, 333, 1234.5]
&gt;&gt;&gt; del a[0]
&gt;&gt;&gt; a
[1, 66.25, 333, 333, 1234.5]
&gt;&gt;&gt; del a[2:4]
&gt;&gt;&gt; a
[1, 66.25, 1234.5]
</pre></div>
<P>
<tt class="keyword">del</tt> can also be used to delete entire variables:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; del a
</pre></div>
<P>
Referencing the name <code>a</code> 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><A NAME="tuples"></A>
<BR>
5.3 Tuples and Sequences
</H1>
<P>
We saw that lists and strings have many common properties, such as
indexing and slicing operations. They are two examples of
<a class="ulink" href="../lib/typesseq.html"
><em>sequence</em> data types</a>. Since
Python is an evolving language, other sequence data types may be
added. There is also another standard sequence data type: the
<em>tuple</em>.
<P>
A tuple consists of a number of values separated by commas, for
instance:
<P>
<div class="verbatim"><pre>
&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></div>
<P>
As you see, on output tuples are always 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. For example: (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). It is also possible to create tuples which contain mutable
objects, such as lists.
<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>
<div class="verbatim"><pre>
&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></div>
<P>
The statement <code>t = 12345, 54321, 'hello!'</code> is an example of
<em>tuple packing</em>: the values <code>12345</code>, <code>54321</code> and
<code>'hello!'</code> are packed together in a tuple. The reverse operation
is also possible:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; x, y, z = t
</pre></div>
<P>
This is called, appropriately enough, <em>sequence unpacking</em>.
Sequence unpacking requires the list of variables on the left to
have the same number of elements as the length of the sequence. Note
that multiple assignment is really just a combination of tuple packing
and sequence unpacking!
<P>
There is a small bit of asymmetry here: packing multiple values
always creates a tuple, and unpacking works for any sequence.
<P>
<H1><A NAME="SECTION007400000000000000000"></A><A NAME="sets"></A>
<BR>
5.4 Sets
</H1>
<P>
Python also includes a data type for <em>sets</em>. A set is an unordered
collection with no duplicate elements. Basic uses include membership
testing and eliminating duplicate entries. Set objects also support
mathematical operations like union, intersection, difference, and
symmetric difference.
<P>
Here is a brief demonstration:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
&gt;&gt;&gt; fruit = set(basket) # create a set without duplicates
&gt;&gt;&gt; fruit
set(['orange', 'pear', 'apple', 'banana'])
&gt;&gt;&gt; 'orange' in fruit # fast membership testing
True
&gt;&gt;&gt; 'crabgrass' in fruit
False
&gt;&gt;&gt; # Demonstrate set operations on unique letters from two words
...
&gt;&gt;&gt; a = set('abracadabra')
&gt;&gt;&gt; b = set('alacazam')
&gt;&gt;&gt; a # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
&gt;&gt;&gt; a - b # letters in a but not in b
set(['r', 'd', 'b'])
&gt;&gt;&gt; a | b # letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
&gt;&gt;&gt; a &amp; b # letters in both a and b
set(['a', 'c'])
&gt;&gt;&gt; a ^ b # letters in a or b but not both
set(['r', 'd', 'b', 'm', 'z', 'l'])
</pre></div>
<P>
<H1><A NAME="SECTION007500000000000000000"></A><A NAME="dictionaries"></A>
<BR>
5.5 Dictionaries
</H1>
<P>
Another useful data type built into Python is the
<a class="ulink" href="../lib/typesmapping.html"
><em>dictionary</em></a>.
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 <em>keys</em>,
which can be any immutable type; strings and numbers can always be
keys. Tuples can be used as keys if they contain only strings,
numbers, or tuples; if a tuple contains any mutable object either
directly or indirectly, it cannot be used as a key. You can't use
lists as keys, since lists can be modified in place using methods like
<tt class="method">append()</tt> and <tt class="method">extend()</tt> or modified with slice and
indexed assignments.
<P>
It is best to think of a dictionary as an unordered set of
<em>key: value</em> pairs, with the requirement that the keys are unique
(within one dictionary).
A pair of braces creates an empty dictionary: <code>{}</code>.
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 <code>del</code>.
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 class="method">keys()</tt> method of a dictionary object returns a list of all
the keys used in the dictionary, in arbitrary order (if you want it
sorted, just apply the <tt class="method">sort()</tt> method to the list of keys). To
check whether a single key is in the dictionary, either use the dictionary's
<tt class="method">has_key()</tt> method or the <tt class="keyword">in</tt> keyword.
<P>
Here is a small example using a dictionary:
<P>
<div class="verbatim"><pre>
&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')
True
&gt;&gt;&gt; 'guido' in tel
True
</pre></div>
<P>
The <tt class="function">dict()</tt> constructor builds dictionaries directly from
lists of key-value pairs stored as tuples. When the pairs form a
pattern, list comprehensions can compactly specify the key-value list.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}
&gt;&gt;&gt; dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension
{2: 4, 4: 16, 6: 36}
</pre></div>
<P>
Later in the tutorial, we will learn about Generator Expressions
which are even better suited for the task of supplying key-values pairs to
the <tt class="function">dict()</tt> constructor.
<P>
When the keys are simple strings, it is sometimes easier to specify
pairs using keyword arguments:
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}
</pre></div>
<P>
<H1><A NAME="SECTION007600000000000000000"></A><A NAME="loopidioms"></A>
<BR>
5.6 Looping Techniques
</H1>
<P>
When looping through dictionaries, the key and corresponding value can
be retrieved at the same time using the <tt class="method">iteritems()</tt> method.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; knights = {'gallahad': 'the pure', 'robin': 'the brave'}
&gt;&gt;&gt; for k, v in knights.iteritems():
... print k, v
...
gallahad the pure
robin the brave
</pre></div>
<P>
When looping through a sequence, the position index and corresponding
value can be retrieved at the same time using the
<tt class="function">enumerate()</tt> function.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; for i, v in enumerate(['tic', 'tac', 'toe']):
... print i, v
...
0 tic
1 tac
2 toe
</pre></div>
<P>
To loop over two or more sequences at the same time, the entries
can be paired with the <tt class="function">zip()</tt> function.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; questions = ['name', 'quest', 'favorite color']
&gt;&gt;&gt; answers = ['lancelot', 'the holy grail', 'blue']
&gt;&gt;&gt; for q, a in zip(questions, answers):
... print 'What is your %s? It is %s.' % (q, a)
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
</pre></div>
<P>
To loop over a sequence in reverse, first specify the sequence
in a forward direction and then call the <tt class="function">reversed()</tt>
function.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; for i in reversed(xrange(1,10,2)):
... print i
...
9
7
5
3
1
</pre></div>
<P>
To loop over a sequence in sorted order, use the <tt class="function">sorted()</tt>
function which returns a new sorted list while leaving the source
unaltered.
<P>
<div class="verbatim"><pre>
&gt;&gt;&gt; basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
&gt;&gt;&gt; for f in sorted(set(basket)):
... print f
...
apple
banana
orange
pear
</pre></div>
<P>
<H1><A NAME="SECTION007700000000000000000"></A><A NAME="conditions"></A>
<BR>
5.7 More on Conditions
</H1>
<P>
The conditions used in <code>while</code> and <code>if</code> statements can
contain any operators, not just comparisons.
<P>
The comparison operators <code>in</code> and <code>not in</code> check whether a value
occurs (does not occur) in a sequence. The operators <code>is</code> and
<code>is not</code> 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. For example, <code>a &lt; b == c</code> tests
whether <code>a</code> is less than <code>b</code> and moreover <code>b</code> equals
<code>c</code>.
<P>
Comparisons may be combined using the Boolean operators <code>and</code> and
<code>or</code>, and the outcome of a comparison (or of any other Boolean
expression) may be negated with <code>not</code>. These have lower
priorities than comparison operators; between them, <code>not</code> has
the highest priority and <code>or</code> the lowest, so that
<code>A and not B or C</code> is equivalent to <code>(A and (not B)) or C</code>.
As always, parentheses can be used to express the desired composition.
<P>
The Boolean operators <code>and</code> and <code>or</code> are so-called
<em>short-circuit</em> operators: their arguments are evaluated from
left to right, and evaluation stops as soon as the outcome is
determined. For example, if <code>A</code> and <code>C</code> are true but
<code>B</code> is false, <code>A and B and C</code> does not evaluate the
expression <code>C</code>. When used as a general value and not as a
Boolean, the return value of a short-circuit operator 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>
<div class="verbatim"><pre>
&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></div>
<P>
Note that in Python, unlike C, assignment cannot occur inside expressions.
C programmers may grumble about this, but it avoids a common class of
problems encountered in C programs: typing <code>=</code> in an expression when
<code>==</code> was intended.
<P>
<H1><A NAME="SECTION007800000000000000000"></A><A NAME="comparing"></A>
<BR>
5.8 Comparing Sequences and Other Types
</H1>
<P>
Sequence objects may be compared to other objects with the same
sequence type. The comparison uses <em>lexicographical</em> 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 sub-sequence of the other, the
shorter sequence is the smaller (lesser) one. Lexicographical
ordering for strings uses the ASCII ordering for individual
characters. Some examples of comparisons between sequences of the
same type:
<P>
<div class="verbatim"><pre>
(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></div>
<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. <A NAME="tex2html3"
HREF="#foot736"><SUP>5.1</SUP></A> Mixed numeric types are compared according to their numeric value, so
0 equals 0.0, etc.
<P>
<BR><HR><H4>Footnotes</H4>
<DL>
<DT><A NAME="foot736">... etc.</A><A
HREF="node7.html#tex2html3"><SUP>5.1</SUP></A></DT>
<DD>
The rules for comparing objects of different types should
not be relied upon; they may change in a future version of
the language.
</DD>
</DL>
<DIV CLASS="navigation">
<div class='online-navigation'>
<p></p><hr />
<table align="center" width="100%" cellpadding="0" cellspacing="2">
<tr>
<td class='online-navigation'><a rel="prev" title="4. More Control Flow"
href="node6.html"><img src='../icons/previous.png'
border='0' height='32' alt='Previous Page' width='32' /></A></td>
<td class='online-navigation'><a rel="parent" title="Python Tutorial"
href="tut.html"><img src='../icons/up.png'
border='0' height='32' alt='Up One Level' width='32' /></A></td>
<td class='online-navigation'><a rel="next" title="6. Modules"
href="node8.html"><img src='../icons/next.png'
border='0' height='32' alt='Next Page' width='32' /></A></td>
<td align="center" width="100%">Python Tutorial</td>
<td class='online-navigation'><a rel="contents" title="Table of Contents"
href="node2.html"><img src='../icons/contents.png'
border='0' height='32' alt='Contents' width='32' /></A></td>
<td class='online-navigation'><img src='../icons/blank.png'
border='0' height='32' alt='' width='32' /></td>
<td class='online-navigation'><a rel="index" title="Index"
href="node19.html"><img src='../icons/index.png'
border='0' height='32' alt='Index' width='32' /></A></td>
</tr></table>
<div class='online-navigation'>
<b class="navlabel">Previous:</b>
<a class="sectref" rel="prev" href="node6.html">4. More Control Flow</A>
<b class="navlabel">Up:</b>
<a class="sectref" rel="parent" href="tut.html">Python Tutorial</A>
<b class="navlabel">Next:</b>
<a class="sectref" rel="next" href="node8.html">6. Modules</A>
</div>
</div>
<hr />
<span class="release-info">Release 2.4.2, documentation updated on 28 September 2005.</span>
</DIV>
<!--End of Navigation Panel-->
<ADDRESS>
See <i><a href="about.html">About this document...</a></i> for information on suggesting changes.
</ADDRESS>
</BODY>
</HTML>