Python Week4 Lecture7 Handout
Python Week4 Lecture7 Handout
PROGRAMMING,
DATA STRUCTURES AND
ALGORITHMS IN PYTHON
Week 4, Lecture 7
for x in l:
x = f(x)
def applylist(f,l):
for x in l:
x = f(x)
Built in function map()
map(f,l) applies f to each element of l
for i in map(f,l):
primelist = []
for i in numberlist:
if isprime(i):
primelist.append(i)
return(primelist)
Selecting a sublist
In general
def select(property,l):
sublist = []
for x in l:
if property(x):
sublist.append(x)
return(sublist)
list(map(square,filter(iseven,range(100))
def square(x):
return(x*x)
def iseven(x):
return(x%2 == 0)
List comprehension
Pythagorean triple: x2 + y2 = z2
{ (x,y,z) | 1 ≤ x,y,z ≤ n, x2 + y2 = z2 }
Extend to lists
List comprehension
for x in range(100):
for y in range(100):
for z in range(100):
Multiple generators
Initialise a 4 x 3 matrix
4 rows, 3 columns
Stored row-wise
l = [ [ 0 for i in range(3) ]
for j in range(4)]
Warning
What’s happening here?
>>> l[1][1] = 7
>>> l
[[0,7,0],[0,7,0],[0,7,0],[0,7,0]]