Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lists Victor Norman CS104. Reading Quiz Q1: What is printed by the following statements? alist = [3, 67, “cat”, [56, 57, “dog”], [ ], 3.14, False] print(3.14.

Similar presentations


Presentation on theme: "Lists Victor Norman CS104. Reading Quiz Q1: What is printed by the following statements? alist = [3, 67, “cat”, [56, 57, “dog”], [ ], 3.14, False] print(3.14."— Presentation transcript:

1 Lists Victor Norman CS104

2 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.True B.False C.Syntax error D.Nothing is printed

3 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]

4 Reading Quiz Q3: What is printed by the following statements? alist = [4, 2, 8, 6, 5] alist[2] = True print(alist) A.[4, 2, True, 8, 6, 5] B.[4, 2, True, 6, 5] C.Syntax Error

5 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.

6 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.” ]

7 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.

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

9 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.

10 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.

11 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 – lst.sort(): returns None – lst.count( ): returns integer

12 Clicker Set 2, Q 1 a = [1, 2, 3, 4] b = a b[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.

13 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

14 Lists, week 2 Reading Quiz

15 Reading Quiz, Q1 myname = “Edgar Allan Poe” namelist = myname.split() init = “” for aname in namelist: init = init + aname[0] print(init) What is printed? A.Poe B.EdgarAllanPoe C.EAP D.William Shakespeare

16 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.

17 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.

18 Item-based vs Index-based Iteration item-based: for in : – is each item in the sequence. index-based: for in range(len( )): – code in the body has the index of what item to deal with, as someSeq[idx] ).

19 Item-based vs Index-based Example # item based fruits = [ ‘banana’, ‘raspberry’, ‘mango’ ] for fruit in fruits: print(“Defend yourself with a”, fruit) # index based for 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

20 Passing lists as parameters Consider this code: def changeVal(x): x = x + 1 y = 7 changeVal(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”.

21 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.

22 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 ]

23 Lists as return values A function can return a list. import random def 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)

24 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

25 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’]

26 Processing CSV file # data file, in this format. # Lastname, firstname, student id, grade Norman, Victor, 0040471, A Idiot, Village, 0012345, F Norman, 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 …

27 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.

28 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.

29 Example Usage (x, y) coordinates. (r, g, b) values to represent a color. (‘love’, ‘marriage’). Things that go together like a (‘horse’, ‘carriage’)

30 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 ] )

31 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]


Download ppt "Lists Victor Norman CS104. Reading Quiz Q1: What is printed by the following statements? alist = [3, 67, “cat”, [56, 57, “dog”], [ ], 3.14, False] print(3.14."

Similar presentations


Ads by Google