1. tuples:
(3) -> 3 but (3,) indicates a tuple -> (3,)
2. tuples and lists:
tuples:num = (1,2,3) (3,) 不可修改 num(1) = 4 -> 'error' can
lists:num = [1,2,3] [3] 可以修改 num[1] = 4 -> [1,4,3] cannot be used as keys
You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
.## universities
Techs = ['MIT', 'Cal Tech'] Ivys = ['Harvard', 'Yale', 'Brown'] Univs = [Techs, Ivys] Univs1 = [['MIT', 'Cal Tech'], ['Harvard', 'Yale', 'Brown']] Techs.append('RPI') print('Univs = ') print(Univs) print('') print('Univs1 =') print(Univs1) for e in Univs: print('Univs contains ') print(e) print(' which contains') for u in e: print(' ' + u)
4. list.append: side affect but '+' creates a new list
5. Avoid mutating a list over which one is iterating
def removeDups(L1, L2): for e1 in L1: if e1 in L2: L1.remove(e1) L1 = [1,2,3,4] L2 = [1,2,5,6] removeDups(L1, L2) print(L1) """ Inside for loop, Python keeps track of where it is in list using internal counter When we mutate a list, we change its length but Python doesn’t update counter """ //Better is to clone def removeDupsBetter(L1, L2): L1Start = L1[:] //Do not use L1Start = L1, not efficient for e1 in L1Start: if e1 in L2: L1.remove(e1) L1 = [1,2,3,4] L2 = [1,2,5,6] removeDupsBetter(L1, L2) print(L1)
6. Difference
alist = range(1,6) blist = alist print alist print blist alist[2] = 'hello' print alist print blist //alist == blist for blist binds to alist clist = range(1,6) dlist = [] for num in alist: clist.append(num) print clist print dlist clist[2] = 'hello' print clist print dlist // clist != dlist
7. map(function, iterable, ...)
Apply function to every item of iterable and return a list of the results.
8. error
monthNumbers = {‘Jan’:1, ‘Feb’:2, ‘Mar’:3, 1:’Jan’, 2:’Feb’, 3:’Mar’}
monthNumbers[‘Jan’] returns 1 but monthNumbers[1] can't returns ‘Jan’ 'error'