z = [1,2,3,4,5,6,7,8,9,10]
z[3:6] = ["a","b","c"]
z
z[3:6] = ["a", "b"] * 2
z
z[4:]=[]
z
z[:0] = ["al", "be"]
z
"a" in "cat"
"a" in "entebbe"
"a" in ("c", "a", "t")
2 in [1,2,3,4,5]
2 in [1,4,"92",2.4]
for x in ["Midterms", "ain’t", "cool"]:
print (x,len(x))
for c in "chimichanga":
print (c*3)
Quiz
What is the value of s
after executing the following program?
s = 0
z = (1,2,3,4.0,"5") #tuple
for i in z:
s = s+i
s
s = 0
z = (1,2,3,4.0,"5") #tuple
for i in z:
s = s+i
s = 0
z = (1,2,3,4.0,"5") #tuple
for i in z:
s = s+float(i)
s
Itetration + binding
If s is a sequence of tuples/sequences, then we can Bind to individual elements of "subsequences".
craigslist = [("alien",3.50), ("dinosaur",1.90),\
("quiz",100.50), ("quesadilla",3.00),\
("good grade in 314","priceless")]
for i,p in craigslist:
print ("One", i, "costs", p)
Old school For-loops
for(i=0,i<10,i++){
print i;
}
list(range(10))
list(range(5,15)) #fixed upper bound
list(range(15,5,-1)) #step
for x in range(10):
print (x)
def funny_fun(s):
for x in s:
print x
s[len(s):] = [x]
def dup_by_k(s,k):
for x in s:
print (x)
s = s + x*k
return s
dup_by_k("1234", 5)
def dup_by_k(s,k):
for x in s[:]:
print (x)
s = s + x*k
return s
dup_by_k("1234", 5)
Map
def dup(x):
return 2 * x
z = range(10)
list(z)
z = map(dup,z)
list(z)
z = map(dup,"chimichanga")
list(z)
Filter
def even(x):
return int(x)%2==0
result = filter(even,range(20))
print(list(result))
result = filter(even,"1234096001234125")
print(list(result))
result = filter(even,(1,2.0,3.2,4))
print(list(result))
Reduce
from functools import reduce
def add(x,y): # x is accumulator and y is list element
return x+y
l = range(10)
print ("l = ", l)
reduce(add, l, 0)
def fac(x):
def mul(x,y): # x is accumulator and y is list element
return x*y
l = list(range(1, x+1))
print ("l = ", l)
return reduce(mul, l, 1)
fac(5)
List Comprehension
[ x*x for x in range(10)]
[2*x for x in "yogurt cheese"]
List Comprehension
[ x*x for x in range(10) if even(x)]
[ 2*x for x in "0123456" if even(x)]
craigslist
[z[0] for z in craigslist if type(z[1])==float and z[1]<3.0]
List Comprehension
for
to iterate over multiple sequences[(x,y) for x in range(3) for y in range(3)]
[(x,y) for x in range(3) for y in range(3) if x > y]
def sort(L):
if L==[]:
return L
else:
l=sort([x for x in L[1:] if x < L[0]])
r=sort([x for x in L[1:] if x >= L[0]])
return(l+L[0:1]+r)
sort([5,3,1,4,2])
d = {}
d["ceviche"] = 3.95
d["burrito"] = 3.50
d
d["burrito"]
d.keys()
d.values()
def freq(s):
d={}
for c in s:
if c in d:
d[c]+=1
else:
d[c]=1
return d
def plotfreq(s):
d=freq(s)
for k in d.keys():
print (k, "*"*d[k])
return d
d=plotfreq([1, 1, 3.0, "A", 3.0, "A", "A", 1, 2, 3.0, 1, "A"])
d
d = plotfreq("avrakedavra")
d