Working with Lists -- Thematic Tutorials v4.7.rc0
system:sage


<div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index" accesskey="I">index</a></li>
  
    
      <a href="../../index.html"><img src="../_static/sagelogo.png" style="vertical-align: middle" title="Sage Logo"></a>
    
  
  
        <li><a href="../index.html">Thematic Tutorials v4.7.rc0</a> &raquo;</li>
 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="working-with-lists">
<span id="siena-tutorials-worksheet02-lists"></span><h1>Working with Lists<a class="headerlink" href="#working-with-lists" title="Permalink to this headline">¶</a></h1>
<p><em>Author: Franco Saliola &lt;saliola at gmail.com&gt;</em></p>
<p>To create a <em>list</em>  of objects, use square brackets.</p>
<ol class="arabic">
<li><p class="first">Create the list  <tt class="docutils literal"><span class="pre">[63,</span> <span class="pre">12,</span> <span class="pre">-10,</span> <span class="pre">'a',</span> <span class="pre">12]</span></tt> , assign it to the variable
<tt class="docutils literal"><span class="pre">L</span></tt> , and print the list. (<em>Hint</em> : Variable assignment in Sage/Python is
done with  <tt class="docutils literal"><span class="pre">=</span></tt> . For example,  <tt class="docutils literal"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">3</span></tt>  defines the <tt class="docutils literal"><span class="pre">a</span></tt> to be  <tt class="docutils literal"><span class="pre">3</span></tt>.)</p>
<div class="highlight-python">

{{{id=0|
# edit here
///
}}}

</div>
</li>
<li><p class="first">Use the  <tt class="docutils literal"><span class="pre">len</span></tt>  command to find the length of the list <tt class="docutils literal"><span class="pre">L</span></tt>.</p>
<div class="highlight-python">

{{{id=1|
# edit here
///
}}}

</div>
</li>
<li><p class="first">To access an element of the list, use the syntax  <tt class="docutils literal"><span class="pre">L[i]</span></tt> , where  <tt class="docutils literal"><span class="pre">i</span></tt>
is the index of the item. What is  <tt class="docutils literal"><span class="pre">L[3]</span></tt>?</p>
<div class="highlight-python">

{{{id=2|
# edit here
///
}}}

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

{{{id=3|
# edit here
///
}}}

</div>
</li>
<li><p class="first">What is the index of the first item of  <tt class="docutils literal"><span class="pre">L</span></tt>?</p>
<div class="highlight-python">

{{{id=4|
# edit here
///
}}}

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

{{{id=5|
# edit here
///
}}}

</div>
</li>
<li><p class="first">Access the last item in  <tt class="docutils literal"><span class="pre">L</span></tt>.</p>
<div class="highlight-python">

{{{id=6|
# edit here
///
}}}

</div>
</li>
</ol>
<p>An important concept about lists is that (like dictionaries, but unlike many
objects in Sage), they can be directly changed. This property is known as
<em>mutability</em>.</p>
<ol class="arabic">
<li><p class="first">Change  <tt class="docutils literal"><span class="pre">L[3]</span></tt>  to  <tt class="docutils literal"><span class="pre">17</span></tt>.</p>
<div class="highlight-python">

{{{id=7|
# edit here
///
}}}

</div>
</li>
</ol>
<p>This concept can lead to some confusion at first. See if you can guess what
the output of the following commands will be.:</p>
<div class="highlight-python">

{{{id=8|
a = [1,2,3]
b = a
b[0] = 7
print a, b
///
}}}

</div>
<p>This result makes sense when you understand that <tt class="docutils literal"><span class="pre">a</span></tt> and <tt class="docutils literal"><span class="pre">b</span></tt> are both labels
attached to the same list. Compare that result with the following.:</p>
<div class="highlight-python">

{{{id=9|
a = 2
b = a
b = b + 1
print a, b
///
}}}

</div>
<p>In this case, we changed the object that <tt class="docutils literal"><span class="pre">b</span></tt> is attached to (to the object
<tt class="docutils literal"><span class="pre">2</span></tt> plus the object <tt class="docutils literal"><span class="pre">1</span></tt>, which is the object <tt class="docutils literal"><span class="pre">3</span></tt>), while <tt class="docutils literal"><span class="pre">a</span></tt> continues
to be attached to the object <tt class="docutils literal"><span class="pre">2</span></tt>. This concept will be useful to keep in
mind, as we discuss some methods which can be used to modify lists.</p>
<ol class="arabic">
<li><p class="first">By typing  <tt class="docutils literal"><span class="pre">L.&lt;tab</span> <span class="pre">key&gt;</span></tt>, you get a list of methods for <tt class="docutils literal"><span class="pre">L</span></tt>. Use one
of these methods to  <em>append</em>  17 to the end of  <tt class="docutils literal"><span class="pre">L</span></tt>.</p>
<div class="highlight-python">

{{{id=10|
# edit here
///
}}}

</div>
</li>
<li><p class="first">Insert the letter &#8216;b&#8217; at index position 2 (do not <em>change</em> the element in
position 2, but add a new element).</p>
<div class="highlight-python">

{{{id=11|
# edit here
///
}}}

</div>
</li>
<li><p class="first">Remove the second occurrence of <img class="math" src="../_images/math/edf074831eb5bc9e61d6d6e09f525a86e3068f6a.png" alt="12"> from <tt class="docutils literal"><span class="pre">L</span></tt>.</p>
<div class="highlight-python">

{{{id=12|
# edit here
///
}}}

</div>
</li>
<li><p class="first">Redefine <tt class="docutils literal"><span class="pre">L</span></tt> to be the list <tt class="docutils literal"><span class="pre">[3,</span> <span class="pre">1,</span> <span class="pre">4,</span> <span class="pre">1,</span> <span class="pre">5,</span> <span class="pre">-1,</span> <span class="pre">0]</span></tt>.</p>
<div class="highlight-python">

{{{id=13|
# edit here
///
}}}

</div>
</li>
<li><p class="first">Reverse the list <tt class="docutils literal"><span class="pre">L</span></tt>.</p>
<div class="highlight-python">

{{{id=14|
# edit here
///
}}}

</div>
</li>
<li><p class="first">Sort the list <tt class="docutils literal"><span class="pre">L</span></tt>.</p>
<div class="highlight-python">

{{{id=15|
# edit here
///
}}}

</div>
</li>
</ol>
<ol class="arabic">
<li><p class="first">Guess the result of the following commands.</p>
<blockquote>
<div class="highlight-python">

{{{id=16|
L = [3, 1, 2]
M = L.sort()
print L, M
///
}}}

</div>
</blockquote>
</li>
<li><p class="first">Now try the following.</p>
<blockquote>
<div class="highlight-python">

{{{id=17|
L = [3, 1, 2]
M = sorted(L)
print L, M
///
}}}

</div>
</blockquote>
</li>
</ol>
<div class="section" id="the-range-command">
<h2>The range command<a class="headerlink" href="#the-range-command" title="Permalink to this headline">¶</a></h2>
<p>The  <tt class="docutils literal"><span class="pre">range</span></tt>  command provides an easy way to construct a list of integers.</p>
<ol class="arabic">
<li><p class="first">Read the documentation (type:  <tt class="docutils literal"><span class="pre">range?</span></tt>  and hit enter or tab). Use it to
create the list <img class="math" src="../_images/math/e03125a1c7bc131925b2596bbe47e96d9860ecdb.png" alt="[1,2,\ldots,50]">.</p>
<div class="highlight-python">

{{{id=18|
# edit here
///
}}}

</div>
</li>
<li><p class="first">Create the list of even numbers between 1 and 100 (including 100).</p>
<div class="highlight-python">

{{{id=19|
# edit here
///
}}}

</div>
</li>
<li><p class="first">The  <tt class="docutils literal"><span class="pre">step</span></tt>  argument in the  <tt class="docutils literal"><span class="pre">range</span></tt>  command can be negative. Use
<tt class="docutils literal"><span class="pre">range</span></tt>  to construct the list <img class="math" src="../_images/math/ab89d518382daa42f0affe3b98ad870f7e76be02.png" alt="[10, 7, 4, 1, -2]">.</p>
<div class="highlight-python">

{{{id=20|
# edit here
///
}}}

</div>
</li>
<li><p class="first">Sage (<em>but not Python!</em>) includes syntax to simplify creating lists like
the above easier. What is the output of the command  <tt class="docutils literal"><span class="pre">[2,</span> <span class="pre">4,</span> <span class="pre">..,</span> <span class="pre">100]</span></tt> ?</p>
<div class="highlight-python">

{{{id=21|
# edit here
///
}}}

</div>
</li>
<li><p class="first">Create the list <img class="math" src="../_images/math/5f9a0dc681561c626bc7ab62872d1335c86f817b.png" alt="[1, 1.5, 2.0, 2.5, ..., 5]"> using Sage&#8217;s special
syntax. Compare this with the output of  <tt class="docutils literal"><span class="pre">range(1,5,0.5)</span></tt> .</p>
<div class="highlight-python">

{{{id=22|
# edit here
///
}}}

</div>
</li>
</ol>
</div>
<div class="section" id="list-comprehensions">
<h2>List Comprehensions<a class="headerlink" href="#list-comprehensions" title="Permalink to this headline">¶</a></h2>
<p>We already know how to create the list <img class="math" src="../_images/math/188afd37056e77ddf9fc78085adefbee7bf9bad0.png" alt="[1, 2, \ldots, 10]">:</p>
<div class="highlight-python">

{{{id=23|
range(1,11)
///
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}}}

</div>
<p>Using a <em>list comprehension,</em> we can now create the list <img class="math" src="../_images/math/612c3309fa0ff057878ad5dda81d2b876d078974.png" alt="[1^2, 2^2,
3^2, ..., 10^2]"></p>
<div class="highlight-python">

{{{id=24|
[i^2 for i in range(1,11)]
///
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
}}}

</div>
<p><strong>Exercises:</strong></p>
<ol class="arabic">
<li><p class="first">Create two lists:</p>
<div class="math">
<p><img src="../_images/math/77c59edff5c7216105abe4e11436287296b42f45.png" alt="x = [1, 2, \ldots, 100] \\
y = [1^2, 2^2, \ldots, 100^2]"></p>
</div><div class="highlight-python">

{{{id=25|
# edit here
///
}}}

</div>
</li>
<li><p class="first">Use a list comprehension to construct the list</p>
<div class="math">
<p><img src="../_images/math/c3ba44f6710c10c2810cdb5223f22a0ee709120a.png" alt="[x_0 + y_0, x_1 + y_1, \ldots, x_{99}+y_{99}]"></p>
</div><div class="highlight-python">

{{{id=26|
# edit here
///
}}}

</div>
</li>
<li><p class="first">Using a list comprehension and the command  <tt class="docutils literal"><span class="pre">sum</span></tt>, compute</p>
<div class="math">
<p><img src="../_images/math/c9b2e222dc0bda00ed26555120b855b733e85152.png" alt="\sum_{i=0}^{99} x_i y_i"></p>
</div><div class="highlight-python">

{{{id=27|
# edit here
///
}}}

</div>
</li>
</ol>
</div>
<div class="section" id="id1">
<h2><a class="reference external" href="http://projecteuler.net/index.php?section=problems&id=6">Project Euler Problem 6</a><a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h2>
<p>The sum of the squares of the first ten natural numbers is:</p>
<div class="math">
<p><img src="../_images/math/0b6aefa457240907fd8775cd70b4c04dd99829e2.png" alt="1^2 + 2^2 + 3^2 + ... + 10^2 = 385"></p>
</div><p>The square of the sum of the first ten natural numbers is:</p>
<div class="math">
<p><img src="../_images/math/2d06ff7e25059e8d5277f0934a16a2472b4a5ae7.png" alt="(1 + 2 + ... + 10)^2 = 3025"></p>
</div><p>Hence the difference between the sum of the squares of the first ten natural
numbers and the square of the sum is</p>
<div class="math">
<p><img src="../_images/math/a8e54fe03356942969f4c1ac9372cd7291a4097f.png" alt="3025 - 385 = 2640"></p>
</div><p>Find the difference between the sum of the squares of the first one hundred
natural numbers and the square of the sum.</p>
<div class="highlight-python">

{{{id=28|
# edit here
///
}}}

</div>
</div>
<div class="section" id="filtering-lists-with-a-list-comprehension">
<h2>Filtering lists with a list comprehension<a class="headerlink" href="#filtering-lists-with-a-list-comprehension" title="Permalink to this headline">¶</a></h2>
<p>A list can be <em>filtered</em> using a list comprehension. For example, to create a
list of the squares of the prime numbers between 1 and 100, we use a list
comprehension as follows:</p>
<div class="highlight-python">

{{{id=29|
[p^2 for p in [1,2,..,100] if is_prime(p)]
///
}}}

</div>
<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. <em>Hints:</em></p>
<blockquote>
<ul class="simple">
<li>To get the remainder of 7 divided by 3 use <tt class="docutils literal"><span class="pre">7</span> <span class="pre">%</span> <span class="pre">3</span></tt>.</li>
<li>To test for equality use two equal signs (<tt class="docutils literal"><span class="pre">==</span></tt>); for example, <tt class="docutils literal"><span class="pre">3</span> <span class="pre">==</span> <span class="pre">7</span></tt>.</li>
</ul>
</blockquote>
<div class="highlight-python">

{{{id=30|
# edit here
///
}}}

</div>
</div>
<div class="section" id="id2">
<h2><a class="reference external" href="http://projecteuler.net/index.php?section=problems&id=1">Project Euler Problem 1</a><a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h2>
<p>If we list all the natural numbers below 10 that are multiples of 3 or 5, we
get 3, 5, 6 and 9. The sum of these multiples is 23.</p>
<p>Find the sum of all the multiples of 3 or 5 below 1000.</p>
<div class="highlight-python">

{{{id=31|
# edit here
///
}}}

</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="../index.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference internal" href="#">Working with Lists</a><ul>
<li><a class="reference internal" href="#the-range-command">The range command</a></li>
<li><a class="reference internal" href="#list-comprehensions">List Comprehensions</a></li>
<li><a class="reference internal" href="#id1">Project Euler Problem 6</a></li>
<li><a class="reference internal" href="#filtering-lists-with-a-list-comprehension">Filtering lists with a list comprehension</a></li>
<li><a class="reference internal" href="#id2">Project Euler Problem 1</a></li>
</ul>
</li>
</ul>

            <h3>This Page</h3>
            <ul class="this-page-menu">
              <li><a href="../_sources/siena_tutorials/Worksheet02-Lists.txt" rel="nofollow">Show Source</a></li>
            </ul>
          <div id="searchbox" style="display: none">
            <h3>Quick search</h3>
              <p class="searchtip" style="font-size: 90%">
              Enter search terms or a module, class or function name.
              </p>
          </div>
          <script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index">index</a></li>
  
    
      <a href="../../index.html"><img src="../_static/sagelogo.png" style="vertical-align: middle" title="Sage Logo"></a>
    
  
  
        <li><a href="../index.html">Thematic Tutorials v4.7.rc0</a> &raquo;</li>
 
      </ul>
    </div>
    
    <div class="footer">
        &copy; Copyright 2005--2011, The Sage Development Team.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.0.4.
    </div>
    <script type="text/javascript">
/*global jQuery, window */
/* Sphinx sidebar toggle.  Putting this code at the end of the body
 * enables the toggle for the live, static, and offline docs.  Note:
 * sage.misc.html.math_parse() eats jQuery's dollar-sign shortcut. */
var jq = jQuery;  
jq(document).ready(function () {
    var bar, bod, bg, fg, key, tog, wid_old, wid_new, resize, get_state, set_state;
    bod = jq('div.bodywrapper');
    bar = jq('div.sphinxsidebar');
    tog = jq('<div class="sphinxsidebartoggle"></div>');
    
    /* Delayed resize helper.  Not perfect but good enough. */
    resize = function () {
        setTimeout(function () {
            tog.height(bod.height());
        }, 100);
    };
    jq(window).resize(function () {
        resize();
    });
    
    /* Setup and add the toggle. See Sphinx v0.5.1 default.css. */
    fg = jq('div.sphinxsidebar p a').css('color') || 'rgb(152, 219, 204)';
    bg = jq('div.document').css('background-color') || 'rgb(28, 78, 99)';
    wid_old = '230px';
    wid_new = '5px';
    tog.css('background-color', bg)
        .css('border-width', '0px')
        .css('border-right', wid_new + ' ridge ' + bg)
        .css('cursor', 'pointer')
        .css('position', 'absolute')
        .css('left', '-' + wid_new)
        .css('top', '0px')
        .css('width', wid_new);
    bod.css('position', 'relative');
    bod.prepend(tog);
    resize();
    
    /* Cookie helpers. */
    key = 'sphinxsidebar=';
    set_state = function (s) {
        var date = new Date();
        /* Expiry in 7 days. */
        date.setTime(date.getTime() + (7 * 24 * 3600 * 1000));
        document.cookie = key + encodeURIComponent(s) + '; expires=' +
            date.toUTCString() + '; path=/';
    };
    get_state = function () {
        var i, c, crumbs = document.cookie.split(';');
        for (i = 0; i < crumbs.length; i += 1) {
            c = crumbs[i].replace(/^\s+/, '');
            if (c.indexOf(key) === 0) {
                return decodeURIComponent(c.substring(key.length, c.length));
            }
        }
        return null;
    };
    
    /* Event handlers. */
    tog.mouseover(function (ev) {
        tog.css('border-right-color', fg);
    }).mouseout(function (ev) {
        tog.css('border-right-color', bg);
    }).click(function (ev) {
        if (bod.hasClass('wide')) {
            bod.removeClass('wide');
            bod.css('margin-left', wid_old);
            bar.css('width', wid_old);
            bar.show();
            set_state('visible');
        } else {
            set_state('hidden');
            bar.hide();
            bar.css('width', '0px');
            bod.css('margin-left', wid_new);
            bod.addClass('wide');
        }
        resize();
    });
    
    /* Hide the normally visible sidebar? */
    if (get_state() === 'hidden') {
        tog.trigger('click');
    } else {
        set_state('visible');
    }
});
    </script>