<span id="tutorial-programming-python"></span><h1>Tutorial: Programming in Python with Sage</h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name">
<col class="field-body">
<tbody valign="top">
<tr class="field"><th class="field-name">AUTHOR:</th><td class="field-body">Florent Hivert &lt;<a class="reference external" href="mailto:florent.hivert@univ-rouen.fr">florent.hivert&#64;univ-rouen.fr</a>&gt;</td>
</tr>
</tbody>
</table>
<p>This tutorial is an introduction to basic programming in Python/Sage. The
reader is supposed to know the elementary notions of programming but is not
supposed to be familiar with the python language. The memo given here are far
from being exhaustive. In case you need a more complete tutorial, you can have
a look at the <a class="reference external" href="http://docs.python.org/release/2.6.4/tutorial/index.html">Python Tutorial</a>. Also Python's
<a class="reference external" href="http://docs.python.org/release/2.6.4/">documentation</a> and in particular the
<a class="reference external" href="http://docs.python.org/release/2.6.4/library">standard library</a> can be
useful.</p>
<p>A <a href="#id1"><span class="problematic" id="id2">:ref:`more advanced tutorial &lt;tutorial-object-class&gt;`</span></a> present the notion of
objects and classes in Python.</p>

<p class="system-message-title">System Message: ERROR/3 (<tt class="docutils">tutorial-programming-python.rst</tt>, line 20); <em><a href="#id2">backlink</a></em></p>
Unknown interpreted text role &quot;ref&quot;.
<p>Here is a further list of resources for people wanting to learn Python:</p>
<ul class="simple">
<li><a class="reference external" href="http://www.korokithakis.net/tutorials/python">Learn Python in 10 minutes</a> ou en français
<a class="reference external" href="http://mat.oxyg3n.org/index.php?post/2009/07/26/Python-en-10-minutes">Python en 10 minutes</a></li>
<li><a class="reference external" href="http://diveintopython.org/">Dive into Python</a>
is a Python book for experienced programmers. Also available in French,
<a class="reference external" href="http://diveintopython.adrahon.org/">Plongez au coeur de Python</a>, and
<a class="reference external" href="http://diveintopython.org/#languages">other languages</a>.</li>
<li><a class="reference external" href="http://www.ibm.com/developerworks/views/opensource/libraryview.jsp?search_by=Discover+Python+Part|">Discover Python</a>
is a series of articles published in IBM's <a class="reference external" href="http://www.ibm.com/developerworks/">developerWorks</a> technical resource center.</li>
</ul>

<h2>Data structures</h2>
<p>In Python, <em>typing is dynamic</em>; there is no such thing as declaring
variables. The function <tt class="docutils literal">type</tt> returns the type of an object <tt class="docutils literal">obj</tt>. To
convert an object to a type <tt class="docutils literal">typ</tt> just write <tt class="docutils literal">typ(obj)</tt> as in
<tt class="docutils literal"><span class="pre">int(&quot;123&quot;)</span></tt>. The command <tt class="docutils literal">isinstance(ex, typ)</tt> returns whether the
expression <tt class="docutils literal">ex</tt> is of type <tt class="docutils literal">typ</tt>. Specifically, any value is <em>an instance
of a class</em> and there is no difference between class and types.</p>
<p>The symbol <tt class="docutils literal">=</tt> design the affectation to a variable; it should not be
confused with <tt class="docutils literal">==</tt> which design the mathematical equality. Inequality is
<tt class="docutils literal">!=</tt>.</p>
<p>The <em>standard types</em> are <tt class="docutils literal">bool</tt>, <tt class="docutils literal">int</tt>, <tt class="docutils literal">list</tt>, <tt class="docutils literal">tuple</tt>, <tt class="docutils literal">set</tt>,
<tt class="docutils literal">dict</tt>, <tt class="docutils literal">str</tt>.</p>
<ul>
<li><p class="first">The type <tt class="docutils literal">bool</tt> (<em>Booleans</em>) takes two values: <tt class="docutils literal">True</tt> and <tt class="docutils literal">False</tt>. The
boolean operator are denoted by their name <tt class="docutils literal">or</tt>, <tt class="docutils literal">and</tt>, <tt class="docutils literal">not</tt>.</p>
</li>
<li><p class="first">Sage uses <em>exact arithmetic</em> on the integers. For performance reason, it
uses its own type named <tt class="docutils literal">Integer</tt> (whereas python uses the types <tt class="docutils literal">int</tt>
and <tt class="docutils literal">long</tt>).</p>
</li>
<li><p class="first">A <em>list</em> is a data structure which groups values. It is constructed using
brackets as in <tt class="docutils literal">[1, 3, 4]</tt>. The <tt class="docutils literal">range</tt> function creates integer
lists. One can also create lists using <em>list comprehension</em>:</p>
<pre class="literal-block">
[ &lt;expr&gt; for &lt;name&gt; in &lt;iterable&gt; (if &lt;condition&gt;) ]

</pre><p>For example:</p>

{{{id=0|
[ i^2 for i in range(10) if i % 2 == 0 ]
///
[0, 4, 16, 36, 64]
}}}

</li>
<li><p class="first">A <em>tuple</em> is very similar to list; it uses parentheses. The empty tuple is
obtained by <tt class="docutils literal">()</tt> or by the constructor <tt class="docutils literal">tuple()</tt>. If there is only one
element one has to write <tt class="docutils literal">(a,)</tt>. A tuple is <em>immutable</em> (one cannot
change it) but it is <em>hashable</em> (see below). One can also create tuples
using comprehension with the constructor:</p>

{{{id=1|
tuple(i^2 for i in range(10) if i % 2 == 0)
///
(0, 4, 16, 36, 64)
}}}

</li>
<li><p class="first">A <em>set</em> is a data structure which contains values without multiplicities or
order. One create it from a list (or any iterable) with the
constructor <tt class="docutils literal">set()</tt>. The element of a set must be hashable.</p>
<blockquote>
<p>sage: set([2,2,1,4,5])
set([1, 2, 4, 5])</p>
</blockquote>
</li>
<li><p class="first">A <em>dictionary</em> is an association table, which associate values to
keys. keys must be hashable. One create dictionnaire using the constructor
<tt class="docutils literal">dict</tt> or using the syntax:</p>
<pre class="literal-block">
{&nbsp;key1 : value1, key2 : value2 ...}&nbsp;

</pre><p>For example:</p>

{{{id=2|
age = {'toto' : 8, 'mom' : 27}; age
///
{'toto': 8, 'mom': 27}
}}}

</li>
<li><p class="first">Quotes, simple <tt class="docutils literal">' '</tt> or double <tt class="docutils literal">&quot; &quot;</tt> encloses <em>character strings</em>. One
can concatenate them using <tt class="docutils literal">+</tt>.</p>
</li>
<li><p class="first">For lists, tuples, strings, and dictionaries, the <em>indexing operator</em> is
written <tt class="docutils literal">l[i]</tt>. For lists, tuples, and string one can also uses <em>slices</em>
as <tt class="docutils literal"><span class="pre">l[:]</span></tt>, <tt class="docutils literal"><span class="pre">l[:b]</span></tt>, <tt class="docutils literal">l[a:]</tt> ou <tt class="docutils literal">l[a:b]</tt>. Negative indexes start from
the end.</p>
</li>
<li><p class="first">The <tt class="docutils literal">len</tt> function returns the number of elements of a list, a tuple, a
set, a string, or a dictionary. One writes <tt class="docutils literal">x in C</tt> to tests whether <tt class="docutils literal">x</tt>
is in <tt class="docutils literal">C</tt>.</p>
</li>
<li><p class="first">Finally there is a special value called <tt class="docutils literal">None</tt> to denote the absence of a
value.</p>
</li>
</ul>


<h2>Control structures</h2>
<p>In Python, there is no keyword for the beginning and the end of an
instructions block. Block are delimited thanks to indentation. Most of the
time a new block is introduced by <tt class="docutils literal">:</tt>. Python has the following control
structure:</p>
<ul>
<li><p class="first">Conditional instruction:</p>
<pre class="literal-block">
if &lt;condition&gt;:
    &lt;instruction sequence&gt;
[elif &lt;condition&gt;:
    &lt;instruction sequence&gt;]*
[else:
    &lt;instruction sequence&gt;]

</pre></li>
<li><p class="first">inside expression exclusively, one can write:</p>
<pre class="literal-block">
&lt;value&gt; if &lt;condition&gt; else &lt;value&gt;

</pre></li>
<li><p class="first">Iterative instructions:</p>
<pre class="literal-block">
for &lt;name&gt; in &lt;iterable&gt;:
    &lt;instruction sequence&gt;
[else:
    &lt;instruction sequence&gt;]

</pre><pre class="literal-block">
while &lt;condition&gt;:
    &lt;instruction sequence&gt;
[else:
    &lt;instruction sequence&gt;]

</pre><p>The <tt class="docutils literal">else</tt> bloc is executed at the end of the loop if the loop is ended
normally, that is neither by a <tt class="docutils literal">break</tt> of an exception.</p>
</li>
<li><p class="first">In a loop <tt class="docutils literal">continue</tt> jump to the next iteration.</p>
</li>
<li><p class="first">An iterable is an object which can be iterated. Iterable types includes
lists, tuples, dictionaries and strings.</p>
</li>
<li><p class="first">An error (also called exception) is raised by:</p>
<pre class="literal-block">
raise &lt;ErrorType&gt; [, error message]

</pre><p>Usual error includes <tt class="docutils literal">ValueError</tt> and <tt class="docutils literal">TypeError</tt>.</p>
</li>
</ul>


<h2>Functions</h2>

<p class="first admonition-title">Note</p>
<p>Python functions vs. mathematical functions</p>
<p class="last">In what follows, we deal with <em>functions</em> is the sense of <em>programming
languages</em>. Mathematical function are handled by sage in a different
way. In particular it doesn't make sense to do mathematical manipulation
such as addiction or derivation on those kinds of functions.</p>

<p>One defines function using the keyword <tt class="docutils literal">def</tt> as</p>
<pre class="literal-block">
def &lt;name&gt;(&lt;argument list&gt;):
     &lt;instruction sequence&gt;

</pre><p>The result of the function is given thank to the instruction <tt class="docutils literal">return</tt>. When
a function is very short, one can define anonymous function using <tt class="docutils literal">lambda</tt>
(remark that there is no return here):</p>
<pre class="literal-block">
lambda &lt;arguments&gt;: &lt;expression&gt;

</pre><p class="first admonition-title">Note</p>
<p>(functional programming)</p>
<p class="last">Functions are objects as any other objects. On can assign them to
variables return them.</p>



<h2>Exercises</h2>


<h2>Lists</h2>

<h3>Creating Lists I: [Square brackets]</h3>
<p><strong>Example:</strong></p>

{{{id=3|
L = [3, Permutation([5,1,4,2,3]), 17, 17, 3, 51]
L
///
[3, [5, 1, 4, 2, 3], 17, 17, 3, 51]
}}}

<p><strong>Exercise:</strong> Create the list&nbsp;<tt class="docutils literal">[63, 12, <span class="pre">-10,</span> 'a', 12]</tt>, assign it to the
variable <tt class="docutils literal">L</tt>, and print the list.</p>

{{{id=4|

///
}}}

<p><strong>Exercise:</strong> Create the empty list. (You will often need to do this.)</p>

{{{id=5|

///
}}}

<h3>Creating Lists II: range</h3>
<p>The <em>range</em> function provides an easy way to construct a list of
integers. Here is the documentation of the <em>range</em> function. Here is the
inline documentation of the <em>range</em> functions:</p>
<pre class="literal-block">
range([start,] stop[, step]) -&gt; list of integers

Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement). For
example, range(4) returns [0, 1, 2, 3].  The end point is omitted!
These are exactly the valid indices for a list of 4 elements.

</pre><p><strong>Exercise:</strong> Use <em>range</em> to construct the list $[1,2,ldots,50]$.</p>

{{{id=6|

///
}}}

<p><strong>Exercise:</strong> Use <em>range</em> to construct the list of <em>even</em> numbers between 1
and 100 (including 100).</p>

{{{id=7|

///
}}}

<p><strong>Exercise:</strong> The <em>step</em> argument for the <em>range</em> command can be negative. Use
<em>range</em> to construct the list $[10, 7, 4, 1, -2]$.</p>

{{{id=8|

///
}}}

<h3>Creating Lists III: list comprehensions</h3>
<p><em>List comprehensions</em> provide a concise way to create lists from other lists
(or other data types).</p>
<p><strong>Example</strong> We already know how to create the list $[1, 2, dots, 16]$:</p>

{{{id=9|
range(1,17)
///
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
}}}

<p>Using a <em>list comprehension</em>, we can now create the list
$[1^2, 2^2, 3^2, dots, 16^2]$ as follows</p>

{{{id=10|
[i^2 for i in range(1,17)]
///
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256]
}}}


{{{id=11|
sum([i^2 for i in range(1,17)])
///
1496
}}}

<p><strong>Exercice:</strong></p>
<p>The sum of the squares of the first ten natural numbers is</p>
<blockquote>
$(1^2 + 2^2 + ... + 10^2) = 385$</blockquote>
<p>The square of the sum of the first ten natural numbers is</p>
<blockquote>
$(1 + 2 + ... + 10)^2 = 55^2 = 3025$</blockquote>
<p>Hence the difference between the sum of the squares of the first ten natural
numbers and the square of the sum is</p>
<blockquote>
$3025 - 385 = 2640$</blockquote>
<p>Find the difference between the sum of the squares of the first one hundred
natural numbers and the square of the sum.</p>

{{{id=12|

///
}}}


{{{id=13|

///
}}}


{{{id=14|

///
}}}

<h4>Filtering lists with a list comprehension</h4>
<p>A list can be <em>filtered</em> using a list comprehension.</p>
<p><strong>Example:</strong> To create a list of the squares of the prime numbers between 1
and 100, we use a list comprehension as follows.</p>

{{{id=15|
[p^2 for p in [1,2,..,100] if is_prime(p)]
///
[4, 9, 25, 49, 121, 169, 289, 361, 529, 841, 961, 1369, 1681, 1849, 2209, 2809, 3481, 3721, 4489, 5041, 5329, 6241, 6889, 7921, 9409]
}}}

<p><strong>Exercise:</strong> Use a <em>list comprehension</em> to list all the natural numbers below
20 that are multiples of 3 or 5. Hint:</p>
<blockquote>
<ul class="simple">
<li>To get the remainder of 7 divided by 3 use <em>7%3</em>.</li>
<li>To test for equality use two equal signs (<em>==</em>); for example, <em>3 == 7</em>.</li>
</ul>
</blockquote>

{{{id=16|

///
}}}

<h4>Nested list comprehensions</h4>
<p>List comprehensions can be nested!</p>
<p><strong>Examples:</strong></p>

{{{id=17|
[(x,y) for x in range(5) for y in range(3)]
///
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2)]
}}}


{{{id=18|
[[i^j for j in range(1,4)] for i in range(6)]
///
[[0, 0, 0], [1, 1, 1], [2, 4, 8], [3, 9, 27], [4, 16, 64], [5, 25, 125]]
}}}


{{{id=19|
matrix([[i^j for j in range(1,4)] for i in range(6)])
///
[  0   0   0][  1   1   1][  2   4   8][  3   9  27][  4  16  64][  5  25 125]
}}}

<p><strong>Exercise:</strong></p>
<p>A <em>Pythagorean triple</em> is a triple $(x,y,z)$ of <em>positive</em> integers satisfying
$x^2+y^2=z^2$. The Pythagorean triples whose components are at most $10$ are:</p>
<blockquote>
$[(3, 4, 5), (4, 3, 5), (6, 8, 10), (8, 6, 10)],.$</blockquote>
<p>Using a filtered list comprehension, construct the list of Pythagorean triples
whose components are at most $50$.</p>

{{{id=20|

///
}}}


{{{id=21|

///
}}}

<h3>Accessing individual elements of lists</h3>
<p>To access an element of the list, use the syntax <tt class="docutils literal">L[i]</tt>, where $i$ is the
index of the item.</p>
<p><strong>Exercise:</strong></p>
<blockquote>
<ol class="arabic">
<li><p class="first">Construct the list <tt class="docutils literal">L = [1,2,3,4,3,5,6]</tt>. What is <tt class="docutils literal">L[3]</tt>?</p>

{{{id=22|

///
}}}

</li>
<li><p class="first">What is <tt class="docutils literal">L[1]</tt>?</p>

{{{id=23|

///
}}}

</li>
<li><p class="first">What is the index of the first element of <tt class="docutils literal">L</tt>?</p>

{{{id=24|

///
}}}

</li>
<li><p class="first">What is <tt class="docutils literal"><span class="pre">L[-1]</span></tt>? What is <tt class="docutils literal"><span class="pre">L[-2]</span></tt>?</p>

{{{id=25|

///
}}}

</li>
<li><p class="first">What is <tt class="docutils literal">L.index(2)</tt>? What is <tt class="docutils literal">L.index(3)</tt>?</p>

{{{id=26|

///
}}}

</li>
</ol>
</blockquote>


<h3>Modifying lists: changing an element in a list</h3>
<p>To change the item in position <tt class="docutils literal">i</tt> of a list <tt class="docutils literal">L</tt>:</p>

{{{id=27|
L = [&quot;a&quot;, 4, 1, 8]
L
///
['a', 4, 1, 8]
}}}

<!-- link -->

{{{id=28|
L[2] = 0
L
///
['a', 4, 0, 8]
}}}

<h3>Modifying lists: append and extend</h3>
<p>To <em>append</em> an object to a list:</p>

{{{id=29|
L = [&quot;a&quot;, 4, 1, 8]
L
///
['a', 4, 1, 8]
}}}

<!-- link -->

{{{id=30|
L.append(17)
L
///
['a', 4, 1, 8, 17]
}}}

<p>To <em>extend</em> a list by another list:</p>

{{{id=31|
L1 = [1,2,3]
L2 = [7,8,9,0]
print L1
///
[1, 2, 3]
}}}

{{{id=32|
print L2
///
[7, 8, 9, 0]
}}}

<!-- link -->

{{{id=33|
L1.extend(L2)
L1
///
[1, 2, 3, 7, 8, 9, 0]
}}}

<h3>Modifying lists: reverse, sort, ...</h3>

{{{id=34|
L = [4,2,5,1,3]
L
///
[4, 2, 5, 1, 3]
}}}

<!-- link -->

{{{id=35|
L.reverse()
L
///
[3, 1, 5, 2, 4]
}}}

<!-- link -->

{{{id=36|
L.sort()
L
///
[1, 2, 3, 4, 5]
}}}


{{{id=37|
L = [3,1,6,4]
sorted(L)
///
[1, 3, 4, 6]
}}}

<!-- link -->

{{{id=38|
L
///
[3, 1, 6, 4]
}}}

<h3>Concatenating Lists</h3>
<p>To concatenate two lists, add them with the operator <tt class="docutils literal">+</tt>. This is not a commutative operation....</p>

{{{id=39|
L1 = [1,2,3]
L2 = [7,8,9,0]
L1 + L2
///
[1, 2, 3, 7, 8, 9, 0]
}}}

<h3>Slicing Lists</h3>
<p>You can slice a list using the syntax <tt class="docutils literal">L[start : stop : step]</tt>. This will
return a sublist of <tt class="docutils literal">L</tt>.</p>
<p><strong>Exercise:</strong> Below are some examples of slicing lists. Try to guess what the output will be before evaluating the cell.</p>

{{{id=40|
L = range(20)
L
///
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
}}}

<!-- link -->

{{{id=41|
L[3:15]
///
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
}}}

<!-- link -->

{{{id=42|
L[3:15:2]
///
[3, 5, 7, 9, 11, 13]
}}}

<!-- link -->

{{{id=43|
L[15:3:-1]
///
[15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4]
}}}

<!-- link -->

{{{id=44|
L[:4]
///
[0, 1, 2, 3]
}}}

<!-- link -->

{{{id=45|
L[:]
///
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
}}}

<!-- link -->

{{{id=46|
L[::-1]
///
[19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
}}}

<p><strong>Advanced exercise:</strong> The following function combines a loop with the some of
the list operations above. What does the function do?</p>

{{{id=47|
def f(number_of_iterations):
       L = [1]
       for n in range(2, number_of_iterations):
           L = [sum(L[:i]) for i in range(n-1, -1, -1)]
       return numerical_approx(2*L[0]*len(L)/sum(L), digits=50)
///
}}}

<!-- link -->

{{{id=48|
f(10)
///
3.1413810483870967741935483870967741935483870967742
}}}

<h1>Tuples</h1>
<p>A <em>tuple</em> is an <em>immutable</em> list. That is, it cannot be changed once it is
created. The syntax for creating a tuple is to the use parentheses.</p>

{{{id=49|
t = (3, 5, [3,1], (17,[2,3],17), 4)
t
///
(3, 5, [3, 1], (17, [2, 3], 17), 4)
}}}

<p>We can create a tuple from a list, or vice-versa.</p>
<!-- link -->

{{{id=50|
tuple(range(5))
///
(0, 1, 2, 3, 4)
}}}

<!-- link -->

{{{id=51|
list(t)
///
[3, 5, [3, 1], (17, [2, 3], 17), 4]
}}}

<p>Tuples behave like lists in many respects:</p>
<table border="1" class="docutils">
<colgroup>
<col width="30%">
<col width="35%">
<col width="35%">
</colgroup>
<thead valign="bottom">
<tr><th class="head">Operation</th>
<th class="head">Syntax for lists</th>
<th class="head">Syntax for tuples</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>Accessing a letter</td>
<td><tt class="docutils literal">list[3]</tt></td>
<td><tt class="docutils literal">tuple[3]</tt></td>
</tr>
<tr><td>Concatenation</td>
<td><tt class="docutils literal">list1 + list2</tt></td>
<td><tt class="docutils literal">tuple1 + tuple2</tt></td>
</tr>
<tr><td>Slicing</td>
<td><tt class="docutils literal">list[3:17:2]</tt></td>
<td><tt class="docutils literal">tuple[3:17:2]</tt></td>
</tr>
<tr><td>A reversed copy</td>
<td><tt class="docutils literal"><span class="pre">list[::-1]</span></tt></td>
<td><tt class="docutils literal"><span class="pre">tuple[::-1]</span></tt></td>
</tr>
<tr><td>Length</td>
<td><tt class="docutils literal">len(list)</tt></td>
<td><tt class="docutils literal">len(tuple)</tt></td>
</tr>
</tbody>
</table>
<p>Trying to modify a tuple will fail.</p>

{{{id=52|
t = (5, 'a', 6/5)
t
///
(5, 'a', 6/5)
}}}

<!-- link -->

{{{id=53|
t[1] = 'b'
///
Traceback (most recent call last):
TypeError: 'tuple' object does not support item assignment
}}}

<h2>Generators</h2>
<p>&quot;Tuple-comprehension&quot; does not exist.  The syntax produces something called a
generator.  A generator allows you to process a sequence of items one at a
time.  Each item is created when it is needed, and then forgotten.  This can
be very efficient if we only need to use each item once.</p>

{{{id=54|
(i^2 for i in range(5))
///
<generator object <genexpr> at 0x...>
}}}


{{{id=55|
g = (i^2 for i in range(5))
g[0]
///
Traceback (most recent call last):
TypeError: 'generator' object is unsubscriptable
}}}

<!-- link -->

{{{id=56|
[x for x in g]
///
[0, 1, 4, 9, 16]
}}}

<p><tt class="docutils literal">g</tt> is now empty.</p>
<!-- link -->

{{{id=57|
[x for x in g]
///
[]
}}}

<p>A nice 'pythonic' trick is to use generators as the argument to functions.  We
do <em>not</em> need double parentheses for this.</p>

{{{id=58|
sum( i^2 for i in srange(100001) )
///
333338333350000
}}}

<h1>Dictionaries</h1>
<p>A <em>dictionary</em> is another built-in data type. Unlike lists, which are indexed by a range of numbers, dictionaries are &quot;indexed&quot; by <em>keys</em>, which can be any immutable object. Strings and numbers can always be keys (because they are immutable). Dictionaries are sometimes called &quot;associative arrays&quot; in other programming languages.</p>
<p>There are several ways to define dictionaries. One method is to use braces, {}, with comma-separated entries given in the form <em>key:value</em>.</p>

{{{id=59|
d = {3:17, &quot;key&quot;:[4,1,5,2,3], (3,1,2):&quot;goo&quot;, 3/2 : 17}
d
///
{3/2: 17, 3: 17, (3, 1, 2): 'goo', 'key': [4, 1, 5, 2, 3]}
}}}

<p>Dictionaries behave as lists and tuples for several important operations.</p>
<table border="1" class="docutils">
<colgroup>
<col width="28%">
<col width="32%">
<col width="40%">
</colgroup>
<thead valign="bottom">
<tr><th class="head">Operation</th>
<th class="head">Syntax for lists</th>
<th class="head">Syntax for dictionaries</th>
</tr>
</thead>
<tbody valign="top">
<tr><td>Accessing elements</td>
<td><tt class="docutils literal">list[3]</tt></td>
<td><tt class="docutils literal"><span class="pre">D[&quot;key&quot;]</span></tt></td>
</tr>
<tr><td>Length</td>
<td><tt class="docutils literal">len(list)</tt></td>
<td><tt class="docutils literal">len(D)</tt></td>
</tr>
<tr><td>Modifying</td>
<td><tt class="docutils literal">L[3] = 17</tt></td>
<td><tt class="docutils literal"><span class="pre">D[&quot;key&quot;]</span> = 17</tt></td>
</tr>
<tr><td>Deleting items</td>
<td><tt class="docutils literal">del L[3]</tt></td>
<td><tt class="docutils literal">del <span class="pre">D[&quot;key&quot;]</span></tt></td>
</tr>
</tbody>
</table>
<!-- link -->

{{{id=60|
d[10]='a'
d
///
{3/2: 17, 10: 'a', 3: 17, (3, 1, 2): 'goo', 'key': [4, 1, 5, 2, 3]}
}}}

<p>A dictionary can have the same value multiple times, but each key can only
appear once and must be immutable.</p>

{{{id=61|
d = {3: 14, 4: 14}
d
///
{3: 14, 4: 14}
}}}


{{{id=62|
d = {3: 13, 3: 14}
d
///
{3: 14}
}}}


{{{id=63|
d = {[1,2,3] : 12}
///
Traceback (most recent call last):
TypeError: unhashable type: 'list'
}}}

<p>Another way to add items to a dictionary is with the <tt class="docutils literal">update()</tt> method:</p>

{{{id=64|
d = {}
d
///
{}
}}}

<!-- link -->

{{{id=65|
d.update( {10 : 'newvalue', 20: 'newervalue', 3: 14, 'a':[1,2,3]} )
d
///
{'a': [1, 2, 3], 10: 'newvalue', 3: 14, 20: 'newervalue'}
}}}

<p>We can iterate through the <em>keys</em>, or <em>values</em>, or both, of a dictionary.</p>

{{{id=66|
d = {10 : 'newvalue', 20: 'newervalue', 3: 14, 'a':[1,2,3]}
///
}}}

<!-- link -->

{{{id=67|
[key for key in d]
///
['a', 10, 3, 20]
}}}

<!-- link -->

{{{id=68|
[key for key in d.iterkeys()]
///
['a', 10, 3, 20]
}}}

<!-- link -->

{{{id=69|
[value for value in d.itervalues()]
///
[[1, 2, 3], 'newvalue', 14, 'newervalue']
}}}

<!-- link -->

{{{id=70|
[(key, value) for key, value in d.iteritems()]
///
[('a', [1, 2, 3]), (10, 'newvalue'), (3, 14), (20, 'newervalue')]
}}}

<p><strong>Exercise:</strong> Consider the following directed graph.</p>
<img alt="media/graph0.png" src="media/graph0.png">
<p>Create a dictionary whose keys are the vertices of the above directed graph,
and whose values are the lists of the vertices that it points to. For
instance, the vertex 1 points to the vertices 2 and 3, so the dictionary will
look like:</p>
<pre class="literal-block">
d = {&nbsp; ..., 1:[2,3], ... }&nbsp;

</pre>
{{{id=71|

///
}}}

<p>Then try</p>
<!-- skip -->

{{{id=72|
g = DiGraph(d)
g.plot()
///
}}}

<h2>Using Sage types: The srange command</h2>
<p><strong>Example:</strong> Construct a $3 times 3$ matrix whose $(i,j)$ entry is the
rational number $frac{i}{j}$. The integer generated by <tt class="docutils literal">range</tt> are
python <tt class="docutils literal">int</tt>. As a consequence, dividing them does euclidian division.</p>

{{{id=73|
matrix([[ i/j for j in range(1,4)] for i in range(1,4)])
///
[1 0 0][2 1 0][3 1 1]
}}}

<p>Whereas Dividing sage <tt class="docutils literal">Integer</tt> gives a fraction</p>

{{{id=74|
matrix([[ i/j for j in srange(1,4)] for i in srange(1,4)])
///
[  1 1/2 1/3][  2   1 2/3][  3 3/2   1]
}}}

<h2>Modifying lists has consequences!</h2>
<p>Try to predict the results of the following commands.</p>

{{{id=75|
a = [1, 2, 3]
L = [a, a, a]
L
///
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
}}}

<!-- link -->

{{{id=76|
a.append(4)
L
///
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
}}}

<p>Now try these:</p>

{{{id=77|
a = [1, 2, 3]
L = [a, a, a]
L
///
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
}}}

<!-- link -->

{{{id=78|
a = [1, 2, 3, 4]
L
///
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
}}}

<!-- link -->

{{{id=79|
L[0].append(4)
L
///
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
}}}

<p>You can use the command <em>deepcopy</em> to avoid these issues.</p>

{{{id=80|
a = [1,2,3]
L = [deepcopy(a), deepcopy(a)]
L
///
[[1, 2, 3], [1, 2, 3]]
}}}

<!-- link -->

{{{id=81|
a.append(4)
L
///
[[1, 2, 3], [1, 2, 3]]
}}}

<p>The same issues occur with dictionaries.</p>

{{{id=82|
d = {1:'a', 2:'b', 3:'c'}
dd = d
d.update( { 4:'d' } )
dd
///
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
}}}

