a = 10 while a > 1: print a a -=1
The forever loop, (bad but sometimes useful):
a = 10 while True: print a a -= 1 if a > 1: break
def find(l, val): for elem in l: if l == val: print "found it!" break
def do_if(l, func, func2): for elem in l: if not func(elem): continue func2(elem)
Remember that functions can be passed around!
def sum(l): total = 0 for elem in l: total += elem return total
def sum(l): if len(l) == 0: return 0 return l[0] + sum(l[1:])
# okay for i in range(1000): print i # will crash or error, too much memory consumed l = # a list of every book on amazon for i in range(len(l)): print i
In Python 2.6 and above:
>>> import sys >>> sys.getsizeof(1) 24
Not guaranteed to be the same everywhere, just gives you an idea
>>> sys.getsizeof(range(1000)) 8072 >>> sys.getsizeof(range(1000000000)) # WARNING: DO NOT RUN # your computer is now a heater
Calculates the values when needed instead of loading them all into memory.
>>> sys.getsizeof(xrange(1000)) 40 >>> sys.getsizeof(xrange(100000)) 40 >>> sys.getsizeof(xrange(10000000000)) 40
xrange returns an iterator. We will learn to make our own iterators in a future class.
>>> a = set() >>> a.add(1) >>> a.add(2) >>> a.add(1) >>> a set([1, 2])
>>> b = set([1, 1, 1, 2, 3, 4, 5, 5]) >>> b set([1, 2, 3, 4, 5])
Sets are like lists, but with only one copy of each value.
def unique(l): return list(set(l))
Intersection (only elements common to both sets):
>>> a & b set([1, 2])
Union (elements in either set):
>>> a | b set([1, 2, 3, 4, 5])
Difference:
>>> b - a set([3, 4, 5])
Subset:
>>> a <= b True >>> b <= a False
Key/value pairs:
d = {} d["a"] = 1 d["b"] = 2
Top 3 Beatles Albums:
# dict d = {1 : "Sgt. Peppers", 2: "The White Album", 3: "Abbey Road"} # list l = ["Sgt. Peppers", "The White Album", "Abbey Road"]
Which is a better representation?
# dict d = {"The Beatles" : {1 : "Sgt. Peppers", 2: "The White Album", 3: "Abbey Road"}, "Radiohead" : {...}, "The National" : {...} } # list l = [["The Beatles", [..]], ["Radiohead", [..]], ["The National", [..]]]
>>> d = {1 : "Sgt. Peppers", 2: "The White Album", 3: "Abbey Road"} >>> d.keys() [1, 2, 3] >>> d.values() ['Sgt. Peppers', 'The White Album', 'Abbey Road'] >>>
# This prints 50 choice = 'ham'; print { 'pram': 40, 'ham' : 50, 'spam': 30, 'eggs': 2 }[choice]
import collections a = collections.defaultdict(lambda: 4) print a[5] # will print '4'
def sum(l): total = 0 for x in l: total += x return total def length(l): if l == []: return 0 return 1 + length(l[1:]) mylist = {"value" : [1, 2, 3, 4]} mylist["sum"] = sum mylist["length"] = length print mylist["length"](mylist["value"])