lists victor norman cs104. reading quiz q1: what is printed by the following statements? alist = [3,...

31
Lists Victor Norman CS104

Upload: lindsay-boyd

Post on 29-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Lists

Victor NormanCS104

Reading Quiz

Q1: What is printed by the following statements?alist = [3, 67, “cat”, [56, 57, “dog”], [ ], 3.14, False]print(3.14 in alist)

A. TrueB. FalseC. Syntax errorD. Nothing is printed

Reading Quiz

Q2: What is printed by the following statements?alist = [4, 2, 8, 6, 5]alist.insert(2, True)alist.insert(0, False)print(alist)

A. [False, 4, 2, True, 8, 6, 5]B. [4, False, True, 2, 8, 6, 5]C. [False, 2, True, 6, 5]

Reading Quiz

Q3: What is printed by the following statements?alist = [4, 2, 8, 6, 5]alist[2] = Trueprint(alist)

A. [4, 2, True, 8, 6, 5]B. [4, 2, True, 6, 5]C. Syntax Error

Lists

• Our second collection data type– elements are in order (like strings)– indexed from 0 to n – 1 (like strings)– elements may have any type (unlike strings)– are mutable. • Methods or code can change a list after it has been

created.

Creating vs. Indexing

• [ ] used for indexing and slicing– for any sequence (string, list, tuple, dictionary…)

• indexing a list: theListName[anInt]• slicing: item = groceries[1:]• [ ] also used for creating a list– remember: we create a string with “the string”– groceries = [ ‘milk’, ‘bread’, ‘jicama’ ]– weird = [ True, 3.1415926, “I love you.” ]

Lists are Mutable

• Can be changed after creation (unlike strings)• Can be done with indexing on left-hand side of

assignment statement.– groceries[1] = ‘rice’

• Note: cannot append to a list with this. Can only reassign a value in the list to a new value.

CQ Set 1, Q 1

lst = [ ‘abc’, ‘def’, ‘ghi’ ]lst[1] = ‘wxyz’print(len(lst))What is the output of this code?A. 3B. 9C. 10D. 4E. No output: there is an error in the second line.

CQ Set 1, Q 2

aList = range(4)for i in range(len(aList)): aList[i] = aList[i] / 10.0

What is the output of this code?A. [ 0, 1, 2, 3 ]B. [ 0.1, 0.2, 0.3, 0.4 ]C. [ 0, 0.1, 0.2, 0.3 ]D. [ 1, 2, 3, 4 ]E. None of the above: there is an error.

Aliasing

• We read this code:b = 3“Make a variable b refer to the integer 3.”

• a = b“Make a variable a refer to what variable b refers to.”

• So, a and b refer to the same value in memory: they are aliases for the same data.

List Methods

• You should know these:– lst.append(item): returns None– lst.extend(listOfItems): returns None– lst.insert(location, item): returns None– item = lst.pop(): changes lst and returns item– item = lst.pop(<index>): changes lst and returns

item– lst.sort(): returns None– lst.count(<item>): returns integer

Clicker Set 2, Q 1

a = [1, 2, 3, 4]b = ab[2] = “hi”What is the value of a after this code runs?A. [1, 2, 3, 4]B. [1, “hi”, 3, 4]C. [1, 2, “hi”, 3, 4]D. [1, 2, 3, “hi”]E. None of the above.

Clicker Set 2, Q 2

a = [77, 33, 22, 99, 44, 11, 0, 55]a.pop(4)a = a.sort()What is the value of a after this code runs?A. There is an error in the code.B. [22, 33, 77, 99]C. [0, 11, 22, 33, 55, 77, 99]D. [ ]E. None

Lists, week 2

• Reading Quiz

Reading Quiz, Q1myname = “Edgar Allan Poe”namelist = myname.split()init = “”for aname in namelist: init = init + aname[0]print(init)

What is printed?

A. PoeB. EdgarAllanPoeC. EAPD. William Shakespeare

Reading Quiz, Q2

alist = [4, 2, 8, 6, 5]blist = []for item in alist: blist.append(item + 5)print(blist)

What is printed?A. [4, 2, 8, 6, 5]B. [4, 2, 8, 6, 5, 5]C. [9, 7, 13, 11, 10]D. Error: you cannot concatenate inside an append.

Reading Quiz, Q3

a. (x, y) = (y, x)b. v = (y, x)c. (x, y) = (1, 2)d. (x, y, z) = (y, x)Which of the above are legal assignments?A. a., b., c.B. a.C. b., c.D. a., c.E. a., b., c., and d.

Item-based vs Index-based Iteration

• item-based:for <item> in <sequence>:

– <item> is each item in the sequence.• index-based:

for <idx> in range(len(<sequence>)):

– code in the body has the index of what item to deal with, as someSeq[idx]).

Item-based vs Index-based Example

# item basedfruits = [ ‘banana’, ‘raspberry’, ‘mango’ ]for fruit in fruits: print(“Defend yourself with a”, fruit)

# index basedfor idx in range(len(fruits)): print(“Defend yourself with a”, fruits[idx])

range(len(fruits)) [0, 1, 2], one index for each item in list fruits

Passing lists as parameters

• Consider this code:def changeVal(x): x = x + 1y = 7changeVal(y)print(y) # prints 7

• Argument y to changeVal is not changed because the value of y (7) is passed in and integers are immutable, so any change does not “stick”.

Passing lists as parameters (2)

• Consider this code:def changeVal(x): x.append(1)y = [ 7 ]changeVal(y)print(y) # prints [ 7, 1 ]

• Argument y to changeVal is changed because the value of y (a reference to the list [ 7 ]) is passed in. Lists are mutable, so any change to the list “sticks”.– In other words, parameter x is an alias for the argument y.

A change to one is reflected in both.

Whiteboard Exercise

• On your whiteboard, write a function that changes each item in a list of numbers to its absolute value. It takes the list as a parameter. Use built-in function abs().

def absAll(nums): for i in range(len(nums)): nums[i] = abs(nums[i])data = [ 3, -17, 44, -66 ]absAll(data)# data is now [3, 17, 44, 66 ]

Lists as return values

• A function can return a list.

import randomdef makeRandNumList(n, max): “””Make a list of n floats, where each item is a random number from 0 to max.””” res = [] for i in range(n): res.append( random.random() * max ) return res

# get 100 random numbers, each from 0 to 44.rands = makeRandNumList(100, 44)

Whiteboard Exercise

• Write a function getPosValues() that takes a single parameter that is a list of numbers, and returns a new list that contains only the positive numbers from the original list.

def getPosValues(nums): res = [ ] for num in nums: if num >= 0: res.append(num) return res

split()

• split() is a string method• by default, splits the string into a list of strings,

by whitespace• ‘hello world’.split() [ ‘hello’, ‘world’]• Very useful for processing data, e.g., CSV data.– split on commas– ‘hello,world’.split(‘,’) [‘hello’, ‘world’]

Processing CSV file# data file, in this format.# Lastname, firstname, student id, gradeNorman, Victor, 0040471, AIdiot, Village, 0012345, FNorman, Susan, 0070741, A-Average, Joe, 0010101, C+

for line in datafile: fields = line.split(“,”) # fields is list of str # remove leading/trailing whitespace from each # before using it. lname = field[0].strip() id = int(field[2].strip()) … code here …

Tuple Type

• tuple– a type (like list, int, float, etc.)– a sequence of values of any types– immutable– so, just like a list, but immutable.

• Not that useful…• Used often when it “feels” right.• Used when you have to have something immutable

(like a key to a dictionary)• Used to return multiple values from a function.

Tuple Creation

• string creation is with “”, ‘’, etc.– greeting = “Ohio gozaimasu”

• list creation is with [ ].– greetings = [“Ohio gozaimasu”, “G’day, mate” ]

• tuple creation is with ( , )– tupOfGreetings = (“Ohio gozaimasu”, “Aloha” )– The parentheses are not actually necessary, but

always use them.

Example Usage

• (x, y) coordinates.• (r, g, b) values to represent a color.• (‘love’, ‘marriage’) . Things that go together

like a (‘horse’, ‘carriage’)

Whiteboard exercise

• Write a function that returns the mean and median of a list of numbers.

def meanAndMedian(nums): nums.sort() # note: alters in input… not nice. mean = sum(nums) / len(nums) # even number of elements if len(nums) % 2 == 0: median = (nums[len(nums) // 2 - 1] + nums[len(nums) // 2) / 2 else: median = nums[len(nums) // 2)] return (mean, median)

mean, med = meanAndMedian( [ 77, 33, -44, 1000, -3.1 ] )

Tuple assignment

• This works:mean, med = meanAndMedian( someList )

• This works:mAndm = meanAndMedian( someList )– in this case, mAndm is a single variable that is a

tuple. Index it to get values.– mean can be found at mAndm[0]– median is at mAndm[1]