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

advertisement
Q and A for Sections 2.2.5 – 2.2.6
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 2nd-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: 3 + 2 or x + y
Sometimes just: operator operand
Example: -17 or -x
Python also does: operand operator
Example: groceries[3] or groceries.<method>
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
= [ <stuff hidden here…> ]
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 123456
(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, 3.1415, 1.4142]
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 2nd
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.
Download