Q and A for Sections 2.2.5 – 2.2.6 CS 106 Victor Norman Calvin College.

Slides:



Advertisements
Similar presentations
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Advertisements

Arrays A list is an ordered collection of scalars. An array is a variable that holds a list. Arrays have a minimum size of 0 and a very large maximum size.
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Mon Week 9 Excel Alice Project Options: – Project of the Stars Submit by Wed 11:59 Week 9, also submit questions RE-SUBMIT for regular deadline – Regular.
CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Q and A for Sections 1 – CS 106 © 2014 Victor Norman.
Introduction to Computing Science and Programming I
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.
CS 106 Introduction to Computer Science I 02 / 29 / 2008 Instructor: Michael Eckmann.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Fundamentals of Python: From First Programs Through Data Structures
Python Magic Select a Lesson: Why Learn to Code? Basic Python Syntax
Lists Introduction to Computing Science and Programming I.
CS 106 Introduction to Computer Science I 12 / 06 / 2006 Instructor: Michael Eckmann.
This material in not in your text (except as exercises) Sequence Comparisons –Problems in molecular biology involve finding the minimum number of edit.
CS 106 Introduction to Computer Science I 02 / 28 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 17 / 2008 Instructor: Michael Eckmann.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Game Programming © Wiley Publishing All Rights Reserved. The L Line The Express Line to Learning L Line L.
by Chris Brown under Prof. Susan Rodger Duke University June 2012
Lists in Python.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Q and A for Sections 2.6 – 2.8 CS 106 Victor Norman.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
Built-in Data Structures in Python An Introduction.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Week 6. Statistics etc. GRS LX 865 Topics in Linguistics.
Python Let’s get started!.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Python Programing: An Introduction to Computer Science
Q and A for Sections 6.2, 6.3 Victor Norman CS106.
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #003 (February 14, 2015)
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Q and A for Sections 1 – CS 106 © 2015 Victor Norman.
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.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
String and Lists Dr. José M. Reyes Álamo.
Topic: Python Lists – Part 1
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
Containers and Lists CIS 40 – Introduction to Programming in Python
CMSC201 Computer Science I for Majors Lecture 12 – Lists (cont)
CS-104 Final Exam Review Victor Norman.
CS 115 Lecture 8 Structured Programming; for loops
CSC 108H: Introduction to Computer Programming
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
BIT115: Introduction to Programming
Object Oriented Programming (OOP) LAB # 8
CISC101 Reminders Assn 3 due tomorrow, 7pm.
String and Lists Dr. José M. Reyes Álamo.
Remembering lists of values lists
Topics Sequences Introduction to Lists List Slicing
Topics Sequences Introduction to Lists List Slicing
Python Review
CISC101 Reminders Assignment 3 due today.
References Revisted (Ch 5)
Introduction to Computer Science
Presentation transcript:

Q and A for Sections – CS 106 Victor Norman Calvin College

Accessors vs. Mutators These are types of methods – a classification of methods. (Recall a method is something you can execute “on” an object, like a list.) – A method call is a “transaction” between the code making the call and the object. An accessor just gets information about the object and returns it to the caller. A mutator tells the object to change something about itself. A mutator call usually does not return a value to the caller. – A mutator actually returns the special value None.

Remember the difference? Q: Is it important to memorize which methods are accessors and which are mutators? A: You don’t *have* to memorize them. But, you might want to – so you can program more quickly. – If you use a mutator wrong, you can trash your data… Example: sorting a list. N.B.: pop() is the only list mutator method that returns a value.

Store original and sorted list? Q: Is there a way so that you can store the sorted list in groceries without deleting the list altogether? A: If you want to keep the original list and have a sorted list, you have to copy it first, then sort one of them. sort() is a mutator.

List item vs. list index Item is an object in the list. Index is where an item is in the list. – Integer – From 0 to n-1 where there are n items in the list. – Can use negative indices: -1 is the last item in the list; -2 is 2 nd -to-last. Can be especially confusing when you are storing integers in a list. Note that some list accessors return an item, while others return an index.

What is an operator? Q: What is an operator and how does it differ from a method? A: You’ve been working with operators for years: +, -, *, /, etc. Syntax: operand operator operand Example: or x + y Sometimes just: operator operand Example: -17 or -x Python also does: operand operator Example: groceries[3] or groceries.

Create list with literal method Q: Construct a list called data using the literal method. (i.e., don’t use the list() constructor). A: data = []

Again Q: Create a new list called categories that contains 4 strings: ‘pens’, ‘pencils’, ‘highlighters’, ‘markers’ A: categories = [‘pens’, ‘pencils’, ‘highlighters’, ‘markers’ ]

pop() Q: The pop() method removes the _________ element in a list. A: last Q: Calling pop(0) removes the __________ element. A: first

More practice Given this list: people = [ ‘Joshua’, ‘Seth’, ‘Elianna’, ‘Dorthea’ ] Write code to remove ‘Elianna’ from the list, using pop(). Now, replace ‘Joshua’ with ‘Jacob’.

More practice Given this list people = [ ] write code to make a variable last refer to the last person in the list. Now, write code to print the length of the list. Now, write code to print the middle person in the list (assuming there are an odd number of people in the list).

pop() vs. remove() Q: What is the difference between pop() and remove()? A: pop(i) takes an index i (or uses -1 if no index provided). remove(item) searches the list for item and removes it, if found. Note: the parameter i is an optional parameter – you can call pop() with a parameter or not.

range() range(start, stop, step): – start and step are optional; if not, given start is 0 and step is 1. – start, stop, and step have to be integers. – result is a list of integers from start, up to but not including stop, by increments of step. What is… range(3)? range(1, 3) range(n) range(3, 7, 2) range(14, 2, -1)

Class vs. object vs. item Q: What is a list class vs. a list object vs. a list item? A: Class: A class (or type) is like a recipe – it describes a dish to make. A list class describes what a list is and what you can do with it. Object: You have to make the recipe (instantiate it) to get the actual thing to eat – the object or instance. You can make it multiple times to get different objects or instances. Item: A list item is something in a list – could be an integer, a float, string, etc. (We’ll practice using this terminology correctly the whole semester. FN, NSTF.)

Mutator or Accessor? For these list methods, which are mutators and which are accessors?: index() append() sort() reverse() pop() item[i] (  indexing)

Question using pop() Q: What happens if you try this, on list majors that has 67 elements in it, including an element ‘Biology’?: majors.pop(‘Biology’) A: You get a syntax error, because pop() requires an integer index in the list.

Question on indexing Q: What does majors[i] do (where majors is a list and i is an integer)? A: It returns the i-th element in the list majors (which is 0-based).

Combining lists Q: How do you combine two lists? A: Use concatenation operator (+): boys = [ ‘Rocky’, ‘Bear’, ‘Stone’ ] girls = [ ‘Rose’, ‘Charity’, ‘Faith’ ] all = boys + girls

BIG Question Q: Though I understand the usefulness of assigning numbers to variables and things like that for computation, this seems like a very inefficient way to make lists of data when you could instead use a program where you can actually see your list (say, Excel). Why would I want to make a grocery list or a waiting list or something like this in python?

Test your knowledge Q: What is wrong with this code? geeks = [ ‘Harold’, ‘Claude’, ‘Melba’ ] geek = geeks[3] A: The maximum index in the list is 2. This is an IndexError. Q: What if we replace the last line with: geek = geeks[-1] A: nothing wrong: geek has the value ‘Melba’

And, again Q: Good or bad: max = 100 nums = range(0, max) print nums[max] A: Bad. nums is a list which is 0-based (indexed from 0), so max index is max - 1 (99)

range() practice range(5) range(4, 5) range(-7, -2, 2) range(-3) range(-10, -15, -1) What creates [100, 103, 106, 109, …, 199]? What creates [-19, 9, 19]? What creates [8, 7, 6, 5]? What creates all even numbers from 0 to (inclusive)?

list practice Suppose a is a list with 5 elements. Swap the last 2 elements. Suppose a = [“Spam”] and b = [“Eggs”]. Create c having [“Spam”, “Eggs”, “Spam”]. Suppose a is a list with 3 elements. Create palindrome to be a list containing the contents of a followed by the reversed contents of a.

More list practice Suppose a = [“Lumberjack”, [‘ok’, ‘works all night’, ‘sleeps all day’]]. Write code to print out ‘works all night’ which you got out of the list. a = [1.2, 2.3, 3.4, 4.5, 5.6, 6.7, , ] b = [3, 4, 5] print a[b[2]] # what is printed?

Return vs. print Q: Does the method pop() print out the value that was "popped" or does it physically return the value? A: It returns the value to the caller. The caller may print this out to the screen if it wants.

Slicing A way to make a new list out of an existing list, by picking out elements of the existing list. Uses listname[start:stop:step], like range(), but uses [], and is not a function call. (Also, compare to listname[index] which accesses a single element in a list.)

Slicing result Q: I don't quite understand how slicing a list works. Does the new list produced have an automatic name assigned to it or do you need to give it a new name? A: cs106 = [ ‘Justin’, ‘Jacob’, ‘Josh’, ‘Ben’ ] firsttwo = cs106[0:2] (What if you did instead: cs106 = cs106[0:2] ? )

Extra old slides

List vs. object Q: I am not entirely clear on what a list object is and how it differs from on object. I think a list object is just an object in a list, but if there is a more precise difference I am not aware of it. A: Everything in Python is an object: something that has a value and on which operations can be done. A list is an object, and can hold objects in it, in order.

Multiplying a list times an integer Q: Can you explain how you create a list using the multiplication sign? A: It is just a cute way of doubling or tripling a list. I’ve *never* used this in real code… (Multiplication is just addition multiple times.) score = [ 100 ] scores = score * 20 # same as score + score + score + score + score + score + …

Memorizing list functions Q: I’m not sure I’ll be able to memorize all those list accessors and mutators… A: Don’t worry. You won’t have to. I’ll copy page 42 and hand it out to you for your tests.

pop() method Q: I don't completely understand the pop method. Further explanation would be useful. A: pop() is unique. It is both an accessor and a mutator. It is the only method that both changes the list object, and returns a value. It removes the last element in the list and returns it or, when there is an index parameter removes the i-th element and returns it.

Assigning result of mutator Q: What happens to the list when you do: groceries = groceries.sort() ? A: Let’s draw the picture… groceries.sort() returns nothing – it is a mutator. So, assigning the result to a variable makes that variable point to nothing, or “None” in python. Q: Is there any way to retrieve the old contents?

Comparing lists Q: What is returned when you compare two lists with ==? A: The result is True or False – one of the 2 “boolean” values. So, you can write: cs106 = [ … ] cs108 = [ … ] areTheSame = (cs106 == cs108)

Q3 Q: What does this code do? pool = list(house) A: It creates a new list, copies the contents of the list house into it, and assigns the new list the name pool. (list() is a constructor that takes an optional parameter, a list.)

Q4 Q: What function call would you use to simply create a list containing the integers 0, 1, 2, 3, 4, 5 ? A: range(0, 6) (or, range(6): when one parameter is given it is assumed that the given parameter is the 2 nd parameter and that the first is the number 0.)

Q10 Q: How does the list() class’s method append() differ from its method extend()? A: append() takes a value as a parameter. extend() takes a list. (The value given to append() could be a list, but it is treated as a single value and added to the end of the list.)

Q11 Q: Are the list methods sort() and reverse() mutators or accessors or constructors? A: They are mutators. They change the object itself. They do not create or return anything.

Q12 Q: Did you read about and understand the functionality of the methods len(), index(), and the operator in? A: Yes, of course.

Terminology Q: Can we clarify the definition and purposes of accessor, mutator, index, syntax, and semantics? A: Please look at the glossaries at the end of the chapters for concise definitions. All these terms *are* important to know.

pop() vs. remove() vs. insert() Q: Can we through an example of when to use pop vs. remove vs. insert methods? A: Yes. pop() does 2 things: removes an item at a given index (or last item if index not given) and it returns the value. remove() searches the list for the given value and removes it (but returns nothing). insert() adds a new single element into the list at the given position.

List operators Q: What are the operators you can use on a list? A: + : concatenate two lists. * : duplicate a list a number of times (never used…) in : is an item in the list? [n] : access an item at index n

Creating a list with [ ] Q: When we use groceries = ['milk', 'eggs', 'apples', 'oranges'] is this using an operator since it is a short cut method of making the list? A: I don’t think I’d call that an operator. It is just a very convenient way to create a list with specific items in it.

Useful List Methods Q: Which functions would be the most useful to know from page 42? A: See the notes you are about to take (or have taken). Q: Am I supposed to be able to remember all these? A: Prof. Norman will tell you now what you should memorize.

Example of pop() on p 43 Q: I didn't understand the middle example on page 43. Can we go over that? A: Yes! pop(0) removes ‘Kim’ which is at the beginning of the list, leaving waitList with 1 fewer element in it, and ‘Donald’ now at index 0, ‘Grace’ at index 1, etc.

Optional Parameters Q: What is an optional parameter as is used in pop()? A: Many functions take an optional parameter or two. If a caller does not provide a value, a default value is supplied. See the two versions of pop() on page 42.

Pop multiple items? Q: Can you pop() multiple items from a list at once? A: Nope. I can’t think of any way to do that…

Difference between append() and extend() Q: What is the difference between append() and extend()? They both seem to add something to the end of a list. A: append() takes a single item and adds it to the end. extend() takes a list as a parameter and adds each element of the parameter list to the end.

Combining multiple lists Q: I wondered since you can combine two lists using the + sign, is it possible to combine multiple lists at one time? A: Yes, absolutely. l1 + l2 + l3 combines l1 + l2 first to make a new list, then combines that list with l3 to make a new list.

Using help() Q: When would you use help() when developing code for a project? A: You might vaguely recall that there is a good way to do something you need to do to a list, but can’t remember the exact syntax. Using help(list) could help you find that method you are looking for. (Searching with google is often a better way, though.)

Using == with lists Q: I don’t understand how == compares lists. Can you explain? A: It works pretty much exactly as you’d expect. The items in both lists have to have the same values.

Questions about shorthand A couple students mentioned something about writing python in shorthand… Where did you see this in the textbook?

Last paragraph, p 47. Q: Can you explain the code in the last paragraph on page 47? A: Heavens to Murgatroyd, yes! Let’s look at that.