Lecture 8: October 24, 2019
Reading
: §8
Due
: Homework 2, due on October 24 at 11:59pm
Lists
Sequence of values (ints, floats, strings, other lists, etc.)
Denoted by square brackets
[ ]
with values separated by commas
Lists are mutable
How to create a list
Lists and strings [
datecvt.py
]
Program to print words in a line [
lines.py
]
What you can do with lists
Check membership:
in
,
not in
+
: concatenation
*
: repetition
list[a:b]
: slice list from
a
to
b
−1
del list[i]
: delete element
list[i]
;
i
can be a slice
Searching a list
Example use: linear search [
linsearch.py
]
Objects, references, aliasing
For strings, one copy: assume
a = "banana"
After
b = a
or
b = a[:]
, then
a is b
is
True
For lists, multiple copies: assume
A = [ 1, 2, 3 ]
After
B = A
then
A is B
is
True
After
B = A[:]
, then
A is B
is
False
Lists as parameters: can change list elements in function and they are changed in caller [
args2.py
]
Add elements to, remove elements:
L.append(x)
,
L.extend(ls)
,
L.insert(i, x)
,
L.pop()
,
L.remove(x)
Element ordering:
L.reverse()
,
L.sort()
Other:
L.count(x)
,
L.index(x)
More on parameters: named arguments and variable number of arguments [
args3.py
]
Tuples
Used to group data
Like lists, but immutable
isinstance(obj,type)
function
type
is
bool
,
float
,
int
,
list
,
str
,
tuple
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email:
mabishop@ucdavis.edu
MHI 289I, Programming in Health Informatics
Version of October 23, 2019 at 9:52PM
You can also obtain a PDF version of this.