Lists Victor Norman CS104

advertisement
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, 3.1415926, “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
– item = lst.pop(<index>): changes lst and returns
item
– lst.sort(): returns None
– lst.count(<item>): 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 <item> in <sequence>:
– <item> is each item in the sequence.
• index-based:
for <idx> in range(len(<sequence>)):
– 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, 0040471, A
Idiot, Village, 0012345, F
Norman, Susan, 0070741, AAverage, 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 …
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]
Download