Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lists Victor Norman CS104. Reading Quiz Lists Our second collection data type – elements are in order (like strings) – indexed from 0 to n – 1 (like.

Similar presentations


Presentation on theme: "Lists Victor Norman CS104. Reading Quiz Lists Our second collection data type – elements are in order (like strings) – indexed from 0 to n – 1 (like."— Presentation transcript:

1 Lists Victor Norman CS104

2 Reading Quiz

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

4 Creating vs. Indexing [ ] used for indexing and slicing – for any sequence (string, list, tuple, dictionary…) [ ] also used for creating a list – groceries = [ ‘milk’, ‘bread’, ‘jicama’ ] – weird = [ True, 3.1415926, “I love you.” ] indexing a list: item = groceries[1] slicing: items = groceries[:2]

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

6 Socrative, 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.

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

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

9 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

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

11 Socrative, 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

12 Lists, week 2

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

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

15 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] ).

16 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

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

18 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)

19 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

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

21 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 = fields[0].strip() id = int(fields[2].strip()) … code here …

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

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

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

25 Whiteboard exercise Write a function that returns the mean and median of a list of numbers. def meanAndMedian(nums): nums.sort() # note: alters 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 ] )

26 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 Lists Our second collection data type – elements are in order (like strings) – indexed from 0 to n – 1 (like."

Similar presentations


Ads by Google