Lists and Loops¶
Introduction¶
Lists provide a way to represent ordered sequences of data. They are an essential part of programming in Python and you will use them repeatedly in your work.
Loops are a powerful building block for writing programs. They make it possible to write programs that perform repeated work, without having to make copies of the same instructions (lines of code). Loops also make programs easier to read and maintain. They enable us to decide how many times to iterate while a program is running (for instance, based on a calculation or something the user enters), rather than at the time we wrote the program. In fact, it would be impossible to write most programs without loops.
In this lab, you will work with lists and loops. By the end of the lab, you should be able to:
- do basic operations on lists
- use for-loops to write repeated code
- write code to construct new lists
As an example, we’re also going to look at how to plot and integrate real-valued functions.
Getting started¶
Open up a terminal and navigate (cd
) to your
cs121-aut-16-username
directory, where username
is your
CNetID. Run git pull upstream master
to collect the lab materials
and git pull
to sync with your personal repository.
Once you have collected the lab materials, navigate to the lab2
directory and fire up ipython3
.
Lists¶
Before you get started on this section, please run
list_examples.py
in ipython3:
In[4]: run list_examples.py
(The text In[x]:
, where x is an integer, is the ipython3 prompt.)
This file contains a few lists (l0
, l1
, and l2
)
that you will use in the tasks for this section. You can see
the value of a list just by typing its name in
ipython3 (try doing this now to make sure you’ve loaded
list_examples.py
correctly):
In [5]: l0
Out[5]: []
In [6]: l1
Out[6]: [1, 'abc', 5.7, [1, 3, 5]]
In [7]: l2
Out[7]: [10, 11, 12, 13, 14, 15, 16]
Lists provide a way to represent ordered sequences of data. They are an essential part of programming in Python and you will use them repeatedly in your work. In this section, you will practice basic list operations. Each task has one or more links to discussions of the concepts needed to complete the task. Try doing the tasks before you review the concepts.
- [literals] Create a list that contains the values 7, “xyz”, and 2.7.
- [length] Compute the length of list
l1
. - [indexing] Write expressions to retrieve the value
5.7
from listl1
and to retrieve the value5
from the last element ofl1
. - [indexing] Predict what will happen if you evaluate the expression
l1[4]
and then try it out. - [indexing] Predict what happens if you evaluate the expression
l2[-1]
and then try it out. - [indexing] Write a statement to change the value
3
inside the last element ofl1
to15.0
. - [slicing] Write an expression to create a slice containing the elements of index 1 through index 5 (inclusive) of list
l2
. - [slicing] Write an expression to create a slice containing the first three elements of list
l2
. - [slicing] Write an expression to create a slice containing the elements of index 1 through the last element (inclusive) of list
l2
. - [operations] Write code to add four elements to list
l0
using theappend
operation and then extract the index 3 element. How many appends do you need to do? - [operations] Create a new list
nl
by concatenating the resulting value ofl0
withl1
and then update an element ofnl
. Do eitherl0
orl1
change as a result executing these statements?
Loops¶
Loops provide a mechanism for repeatedly performing a computation. They are often used in conjunction with lists in Python. As in the last section, this section contains a collection of tasks with links to discussions of the necessary concepts.
The list tasks were simple enough that you could easily type the
solutions into ipython3 directly. The solutions to the tasks in this
section have multiple lines, so you will want to put your code in a
file (feel free to use list_examples.py
for this purpose) and then
load it into ipython3. We recommend reviewing the Using an editor
section of lab1, before you get started on this section.
Remember to save any changes that you make to the file and re-run it in ipython3.
- [basics] Write a loop to compute a variable
all_pos
that has the valueTrue
if all of the elements in the listl3
are positive andFalse
otherwise. - [loops & append] Write code to create a new list that contains only the positive values in the list
l3
. - [loops & append] Write code that uses append to create a new list
nl
in which the ith element ofnl
has the valueTrue
if the ith element ofl3
has a positive value andFalse
otherwise - [range, list initialization] Write code that uses range and list initialization to create a new list
nl
in which the ith element ofnl
isTrue
if the ith element ofl3
has a positive value andFalse
otherwise. Hint: start by calculating a list of the right length withFalse
at every index. - [range, list initialization] Given a list
l4
that contains values in the range from0
toM
inclusive write code that determinesM
using the built-inmax
function and then creates a new list in which the ith element contains a count of the number of times the value i occurred inl4
.
Integration¶
Now that you have some practice with loops, we move on to a more realistic example.
In this section we will compute definite integrals using numeric quadrature. The definite integral of a function is just the area under the curve of that function between two x values. We can calculate this area by filling in the curve with many small rectangles and then adding up the area of each of the rectangles - this method is aptly named the rectangle method.
In the file integration_lab.py
there is a function
def f(x):
return x*x
This code defines a new function (like print
or math.cos
) that
takes a floating point value as an input and produces a floating point
value as an output. In this sense it is a mathematical function like
sin or log. f
corresponds to the mathematical function \(f(x)
= x^2.\) We will use a for loop to compute the integral of this
function from 0 to 1 using N rectangles.
We have defined a function integrate
that you will use for this
task. Add code to integrate
to perform the following steps.
- Decide on a number of rectangles
N
(10 is a good number to start). - Compute the width (
dx
) of your rectangles. - Create a
totalArea
variable to store the sum of the areas of all the rectangles. Start it at zero. - Make a loop that takes a variable,
i
, from 0 to N. - For each of these steps compute the area of the rectangle as
height*width. Height is the value equal to the
f
function called on eachi*dx
and width isdx
. Add this area tototalArea
. - After the for loop, return the value of
totalArea
using the statement:return totalArea
. - Celebrate, you have just replaced calculus.
Load integration_lab.py
into ipython3 and then give your function
a try by calling: integrate()
.
Errors¶
The value of this integral is
Did your code compute the correct value?
Try your program again but set the number of rectangles to 100 instead. Try 1000.
How many rectangles do you have to use to obtain a result that is correct enough?
A quick lesson in abstraction¶
Changing the value of N
in your function is tedious. Having
multiple copies of your function for different values values of N
is a very bad idea. To fix this problem, we can change the definition
of integrate
to take the number of rectangles as an argument named
N
instead. To see how this approach works, change the header for
integrate
to:
def integrate(N):
and then remove the line that initializes the value of N
. Re-run
integration_lab.py
in ipython3 and then call integrate with
different values for N
(integrate(10)
or integrate(10000)
,
for example).
As you write code over the course of the term, you will want to look for these types of opportunities to exploit abstraction to create more general functions and reduce the amount of duplicated code in your programs.
Plotting functions¶
In this section we will plot the sinc function, which is defined as follows:
Open the file plot_lab.py
and you will see that we have already
defined this function for you under the name sinc
.
This function is similar to f
above, in that it is again a
function in the mathematical sense, and we can draw it on a standard
two dimensional plot as can be seen above.
Python has a very useful library named pylab
that we can use to plot
data. In particular, we’ll be using a function aptly named
pylab.plot
that can help us here. This function takes a list of
floats with the x values and a list of floats with the y values as
arguments, and produces an image of the corresponding x and y points
plotted on a standard axis. We’ll also use the function
pylab.show
, which does not take any arguments, to display the
plot.
In order to see what the sinc function looks like we will need to create lists of x and y values and then give these lists to the plot function.
Part 1¶
In the function plot_sinc
:
- Create and fill
X
with the values-10, -9, -8, ..., 9, 10
using therange
function. - Create an empty list
Y
. - Use a for loop to fill the
Y
list with values equal to thesinc
function called on each of theX
values. - Call
pylab.plot
withX
andY
inputs and then callpylab.show()
to show the plot.
Part 2¶
The function is not clear from this image. The distance between points
is too large. Instead of filling X
with values -10, -9, ...
make a list larger filled with values that are closer together like
-10, -9.9, -9.8, -9.7, ..., -0.1, 0, 0.1, 0.2, 0.3, ..., 9.9, 10
.
The range
function, which you used in Part 1, generates
integer values, but we’d like to use floating point values for the x
values instead. Fortunately, there is an analogous library function
numpy.arange
for floating point values. It takes the same
arguments as range (lower bound, upper bound, increment), but as
floats rather than integers and it generates floats instead of
integers. Change your code to:
- use
numpy.arange
instead ofrange
in the computation ofX
and - take the increment as an argument to
plot_sinc
rather than using a hard-coded value.
Then:
- Plot the function with spacing between x points equal to .1 by calling
plot_sinc(.1)
. - Plot the function with spacing between x points equal to .01 by calling
plot_sinc(.01)
.
When finished¶
When finished with the lab please check in your work (assuming you are inside the lab directory):
git add list_examples.py
git add integration_lab.py
git add plot_lab.py
git commit -m "Finished with lab2"
git push
No, we’re not grading this, we just want to look for common errors.