Introductory Programming Fall 2004 For Thursday you should: 1) Finish homework 6. 2) If you didn't get a check on Eval 4, work on Eval 4b. 3) Prepare for an evaluation on Chapter 8. Homework 6 questions? Lists ----- A list is like a string except 1) the elements can be any type of value 2) lists are mutable Ways to make lists: 1) bracket operators: t = [1, 2, 3] 2) range function t = range(3) 3) list function t = list('allen') Lists and for loops: for x in [1, 2, 3]: print x for x in range(3): print x for x in list('allen'): print x Exercises: 1) write a loop that traverses a list of integers and counts the number of elements that are even now encapsulate it is a function named count_even 2) write a loop that traverses a list of integers and prints each element of the list squared. encapsulate it in a function named print_squares 3) write a loop that traverses a list of integers and adds up the total of all the elements. encapsulate it in a function named list_sum List methods ------------ Many list operations are methods, which are functions that you invoke on a list using dot notation. Try this: t = [1, 2, 3] t.append(4) print t t.reverse() print t import random random.shuffle(t) # just a plain old function in the random module print t t.sort() print t append ------ The append method is often used to build a list incrementally. What does the following function do? def mystery(t): result = [] for x in t: result.append(x**2) return result print mystery(range(4)) Sequences --------- Sequence operations http://www.python.org/doc/current/lib/typesseq.html Mutable sequence operations http://www.python.org/doc/current/lib/typesseq-mutable.html