Lecture 7 — Lists Part 1 ============================== Overview -------- - So far we’ve looked at working with individual values and variables. - This is cumbersome even for just two or three variables. - Think of what you had to do with the scores in HW 1. - We need a way to aggregate multiple values and refer to them using a single variable. Reading: This class meeting and the next are based on Chapter 5 of *Practical Programming*. Lists are Sequences of Values ----------------------------- - Gather together values that have common meaning - As a first example, here are scores of 7 judges for the free skating part of the figure skating competition: :: scores = [ 59, 61, 63, 63, 68, 64, 58 ] - As a second example, here are the names of the planets in the solar system (including Pluto, for now): :: planets = [ 'Mercury', 'Venus', 'Earth', 'Mras', 'Jupiter', 'Saturn', 'Neptune', 'Uranus', 'Pluto' ] - Notes on syntax: - Begin with ``[`` and end with ``]`` - Commas separate the individual values - The spaces between values are optional and are used for clarity here. - Any type of object may be stored in a list, and each list can mix different types. Why bother? ----------- - Gather common values together, providing them with a common name, **especially** when we don’t know how many values we will have. - Apply an operation to the values as a group. - Apply an operation to each value in the group. - Examples of computations on lists: - Average and standard deviation - Which values are above and below the average - Correct mistakes - Remove values (Pluto) - Look at differences - Watch for these themes throughout this lecture and the next. Accessing Individual Values — Indexing -------------------------------------- - Notice that we made the mistake in typing ``'Mras'``. How do we fix this? We’ll start by looking at *indexing*. - The line :: >>> print planets[1] accesses and prints the string at what’s known as index 1 of the list ``planets``. Try it? - Surprised? - Each item / value in the list is associated with a unique index - Indexing in Python (and most other programming languages) starts at 0. - The notation is again to use ``[`` and ``]`` with an integer (non-negative) to indicate which list item. - What is the last index in ``planets``? - We can find the length using :func:`len` and then figure out the answer. - Again, are you surprised? A Memory Model for Lists ------------------------ We’ll draw a memory model in class that illustrates the relationship among - The name of the list - The indices - The values stored in the list Part 1 Exercises ---------------- #. Make a list involving the first five names you can think of and assign this to the variable ``names``. #. What is the index of the first value in ``scores`` that is greater than 65? #. Write a line of Python code to print this value and to print the previous and next values of the list. #. What is the index of the middle value in a list that is odd length? For even length lists, what are the indices of the middle two values? Changing Values in the List --------------------------- - Once we know about indexing, changing a value in a list is easy: :: >>> planets[3] = 'Mars' - This replaces item 3 of ``planets`` with the string ``'Mars'`` - Now we can check the output: :: >>> print planets to make sure we got it right. All Indices Are Not Allowed --------------------------- - If ``t`` is a list, then the items are stored at indices from 0 to ``len(t)-1``. - If you try to access indices at ``len(t)`` or beyond, you get a run-time error. We’ll take a look and see. - If you access negative indices, interesting things happen: :: >>> print planets[-1] Pluto - More specifically, for any list ``t``, if ``i`` is an index from 0 to ``len(t)-1`` then ``t[i]`` and ``t[i-len(t)]`` are the same spot in the list. Functions on Lists: Computing the Average ----------------------------------------- - There are many functions (methods) on lists. We can learn all about them using the ``help`` command. - This is just like we did for strings and for modules, e.g. :: >>> import math >>> help(math) >>> help(str) - Interestingly, we can run help in two ways, one :: help(list) gives us the list methods, and the second :: help(planets) tells us that ``planets`` is a list before giving us list methods. - First, let's see some basic functions on the list values. - The basic functions ``max``, ``sum`` and ``min`` exist for lists as well. - This gives us a simple way to compute the average :math:`\text{CO}_2` level in parts per million: :: >>> print "Average Scores = %.2f" %(sum(scores) / float(len(scores))) Average Scores = 62.29 >>> print "Max Score =", max(scores) Max Score = 68 >>> print "Min Score =", min(scores) Min Score = 58 - Exploring, we will look at what happens when we apply ``sum``, ``max`` and ``min`` to our list of planet names. Can you explain the result? Functions that modify the input: Sorting a list ----------------------------------------------- - We can also sort the values in a list by sorting it. Let's try the following: :: >>> planets = [ 'Mercury', 'Venus', 'Earth', 'Mras', 'Jupiter', \ 'Saturn', 'Neptune', 'Uranus', 'Pluto' ] >>> planets ['Mercury', 'Venus', 'Earth', 'Mras', 'Jupiter', 'Saturn', 'Neptune', 'Uranus', 'Pluto'] >>> planets.sort() >>> planets ['Earth', 'Jupiter', 'Mercury', 'Mras', 'Neptune', 'Pluto', 'Saturn', 'Uranus', 'Venus'] - Note that we did not assign the value returned by sort to a new variable. This is the first function we learnt that modifies the input. Try the following and see what happens: :: >>> scores = [ 59, 61, 63, 63, 68, 64, 58 ] >>> new_scores = scores.sort() >>> scores [58, 59, 61, 63, 63, 64, 68] >>> new_scores >>> - Ok, what is the value of the variable ``new_scores``? It is unclear. Let's try in a different way. :: >>> print scores [58, 59, 61, 63, 63, 64, 68] >>> print new_scores None >>> - So, the function returns nothing! But, it does change the value of the input list. This is the first such function we have seen. - It does so, because lists are containers and functions can manipulate what is inside containers. They cannot do so for simple types like integer and float. More Functions: Appending Values, Inserting Values, Deleting ------------------------------------------------------------ - Now, we will see more functions that can change the value of a list without returning anything. - Armed with this knowledge, we can figure out how to add and remove values from a list: - :func:`append` - :func:`insert` - :func:`pop` - :func:`remove` - These operations are fundamental to any “container” — an object type that stores other objects. - Lists are our first example of a container Exercises --------- #. Write three different ways of removing the last value — ``'Pluto'`` — from the list of planets. Two of these will use the method ``pop``. #. Write code to insert ``'Asteroid belt'`` between ``'Mars'`` and ``'Jupiter'``. Summary ------- - Lists are sequences of values, allowing these values to be collected and processed together. - Individual values can be accessed and changed through indexing. - Functions and methods can be used to **return** important properties of lists like :func:`min`, :func:`max`, :func:`sum`. - Functions and methods can be also used to **modify** lists, but not return anything. Studying for the exam --------------------- Let us try to make a list of the crucial things to review before the exam. - Syntax: can you find syntax errors in code? - Correct variable names, assigning a value to a variable - Output: can you compute the output of a piece of code? - Expressions: operator precedence - The distinction between integer and float division - The distinction between division (4/5) and modulo (4%5) operators, and how they work for positive and negative numbers - Remember shorthands: ``+=``, ``-=``, ``/=``, ``*=``. - Functions: defining functions and using them - Distinguish between variables local to functions and variables that are global - Modules: how to import and call functions that are from a specific module (:mod:`math` is the only one we learnt so far) - How to access variable values defined in a module (see ``math.pi`` for example) - Strings: how to create them, how to escape characters, multi-line strings - String ordering (lexicographic ordering) - How to use :func:`raw_input`: remember it always returns a string - Boolean data type: distinguish between expressions that return integer/float/string/Boolean - Remember the distinction between ``=`` and ``==`` - Boolean value of conditions involving AND/OR/NOT - IF/ELIF/ELSE statements, how to write them. Understand what parts are optional and how they work - Creating, indexing and modifying lists - Remember the same function may work differently and do different things when applied to a different data type - Review all about the different ways to call the print function for multiple line of input :: name = 'Eric Cartman' age = 8 location = 'South Park' print "Option 1: Student name:", name, 'lives at:', location print "Student age:", age print print "Option 2: Student name:", name, 'lives at:', location, "\nStudent age:", age print print "Option 3: Student name: %s lives at: %s Student age: %d" %(name, location, age) print Try and see whether you can predict the output. Now, let's review all the functions we have learnt in this class. - ``+`` (concatenation and addition), ``*`` (replication and multiplication), ``/``, ``%``, ``**`` - :func:`int`, :func:`float`, :func:`str`, :func:`math.sqrt()`, :func:`min`, :func:`max`, :func:`abs`, :func:`round`, :func:`sum`, :func:`string.upper`, :func:`string.lower`, :func:`string.replace`, :func:`string.capitalize`, :func:`list.sort`, :func:`list.insert`, :func:`list.append`, :func:`list.pop`, :func:`list.remove` - Can you tell which data types each apply to and how? - Distinguish between the different types of functions we have learnt in this class: - Functions that take one or more values as input and return something (input objects/values are not modified) :: >>> min(3,2,1) 1 >>> min([3,2,1]) 1 >>> mystr = 'Monty Python' >>> len(mystr) 12 - Functions that take one or more values as input and return nothing (input objects/values are not modified) :: >>> def print_max(val1, val2): ... print "Maximum value is", max(val1, val2) ... >>> x1 = 10 >>> x2 = 15 >>> print_max(x1, x2) Maximum value is 15 - Functions that apply to an object, like a string, and return a value (but not modify the object that they apply to) :: >>> mystr = 'Monty Python' >>> mystr.replace('o','x') 'Mxnty Pythxn' >>> mystr 'Monty Python' >>> mystr.upper() 'MONTY PYTHON' >>> mystr 'Monty Python' - Functions that apply to an object, like a list and modify it (but not return anything) :: >>> scores = [3,4,5,1] >>> scores.sort() >>> scores [1, 3, 4, 5] >>> scores.append(6) >>> scores [1, 3, 4, 5, 6] - Local vs. global: Can you guess what each of the print statements print and explain why? :: def f1(x,y): return x+y def f2(x): return x+y x = 5 y = 10 print 'A:', f1(x,y) print 'B:', f1(y,x) print 'C:', f2(x) print 'D:', f2(y) print 'E:', f1(x)