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.

Slides:



Advertisements
Similar presentations
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Advertisements

Course A201: Introduction to Programming 10/28/2010.
Container Types in Python
CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
Python Mini-Course University of Oklahoma Department of Psychology Day 4 – Lesson 15 Tuples 5/02/09 Python Mini-Course: Day 4 – Lesson 15 1.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
Sequences The range function returns a sequence
Lists Introduction to Computing Science and Programming I.
1 Sequences A sequence is a list of elements Lists and tuples – Lists mutable – Tuples immutable Sequence elements can be indexed with subscripts – First.
Strings Victor Norman CS104 Calvin College. Reading Quiz Counts toward your grade.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Q and A for Sections 2.3 – 2.5 CS 106 Professor Victor T. Norman, DDS.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
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.
Course A201: Introduction to Programming 11/04/2010.
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
COMPSCI 101 Principles of Programming Lecture 25 – Nested loops, passing mutable objects as parameters.
Built-in Data Structures in Python An Introduction.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 8 Working.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
Data Collections: Lists CSC 161: The Art of Programming Prof. Henry Kautz 11/2/2009.
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
C++ String Class nalhareqi©2012. string u The string is any sequence of characters u To use strings, you need to include the header u The string is one.
Strings, part 2 Victor Norman CS104 Calvin College.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
Tuples Chapter 10 Python for Informatics: Exploring Information
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 11 Using strings and sequences 5/02/09 Python Mini-Course: Day 3 – Lesson.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
A Tutorial on the Python Programming Language. Overview Running Python and Output Data Types Input and File I/O Control Flow Functions.
1 CS 177 Week 6 Recitation Slides Review for Midterm Exam.
Scope, Aliasing, Tuples & Mutability Intro2CS – week 4a 1.
Python Basics  Functions  Loops  Recursion. Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
CS106 Mid-term Quiz Not counted in your grade.. Q1 Write code to create a variable message that refers to a string Hello world. Answer: message = “Hello.
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Equality, references and mutability COMPSCI 105 SS 2015 Principles of Computer Science.
Indentations makes the scope/block Function definition def print_message (): print “hello” Function usages print_message () hubo.move ()// hubo is a class.
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
Python - Lists.
Containers and Lists CIS 40 – Introduction to Programming in Python
CS 100: Roadmap to Computing
CS-104 Final Exam Review Victor Norman.
Section 6: Sequences Chapter 4 and 5.
More Loop Examples Functions and Parameters
Ruth Anderson University of Washington CSE 160 Spring 2018
CISC101 Reminders Slides have changed from those posted last night…
CS190/295 Programming in Python for Life Sciences: Lecture 6
Data types Numeric types Sequence types float int bool list str
4. sequence data type Rocky K. C. Chang 16 September 2018
String and Lists Dr. José M. Reyes Álamo.
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
CS2011 Introduction to Programming I Arrays (I)
Tuples.
CISC101 Reminders Assignment 2 due today.
COMPUTER PROGRAMMING SKILLS
Python Review
CMSC201 Computer Science I for Majors Lecture 16 – Tuples
CSE 231 Lab 6.
Winter 2019 CISC101 5/26/2019 CISC101 Reminders
Intro to Computer Science CS1510 Dr. Sarah Diesburg
def-ining a function A function as an execution control structure
Introduction to Computer Science
Presentation transcript:

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 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…) [ ] also used for creating a list – groceries = [ ‘milk’, ‘bread’, ‘jicama’ ] – weird = [ True, , “I love you.” ] indexing a list: item = groceries[1] slicing: items = groceries[:2]

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.

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.

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.

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

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.

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

Lists, week 2

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

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.

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

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

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

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, grade Norman, Victor, , A Idiot, Village, , F Norman, Susan, , A- Average, Joe, , 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 …

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