Python

Contents
      1. Python List Comprehension
        1. Ad Infinitum
      2. Pitfalls
              1. Default Parameter Objects

Python List Comprehension

 >>> foo = [1, 2, 3, 4]
 
 # map:
 >>> bar = [x*2 for x in foo]
 >>> bar
 [2, 4, 6, 8]
 
 # filter:
 >>> [x for x in foo if 1 < x < 4]
 [2, 3]
 
 # reduce (foldl):
 >>> import functools
 >>> functools.reduce(lambda x,y: x+y, foo, 0)
 10
 
 # combine (zipWith):
 >>> list(map(lambda x,y: y**x, foo, bar))
 [2, 16, 216, 4096]
 >>> [y**x for x,y in zip(foo,bar)]
 [2, 16, 216, 4096]
 
 # cartesian product:
 >>> [(x,y) for x in foo for y in bar]
 [(1, 2), (1, 4), (1, 6), (1, 8), (2, 2), (2, 4), (2, 6), (2, 8), 
  (3, 2), (3, 4), (3, 6), (3, 8), (4, 2), (4, 4), (4, 6), (4, 8)]

Ad Infinitum

 >>> import itertools
 >>> def take8(iterator): return list(itertools.islice(iterator, 8))
 >>> foo = itertools.count(1)
 # map:
 >>> take8(itertools.imap(lambda x: x*2, foo))
 [2, 4, 6, 8, 10, 12, 14, 16]
 # filter:
 >>> take8(itertools.ifilter(lambda x: x%4==0, foo))
 [12, 16, 20, 24, 28, 32, 36, 40]
 # combine (zipWith):
 >>> bar = itertools.cycle([-1,1])
 >>> take8(itertools.imap(lambda x,y: x*y, foo, bar))
 [-41, 42, -43, 44, -45, 46, -47, 48]
 >>> take8(itertools.starmap(lambda x,y: x*y, itertools.izip(foo, bar)))
 [-49, 50, -51, 52, -53, 54, -55, 56]

Pitfalls

Default Parameter Objects
The default object for optional parameters is shared across calls:
 >>> def appendIfBigger(element, list=[]): # broken!
 ...     if [x for x in list if x >= element] == []:
 ...             list.append(element)
 ...     return list
 ... 
 >>> b = appendIfBigger(2, appendIfBigger(1))
 >>> b
 [1, 2]
 >>> appendIfBigger(4)
 [1, 2, 4]

EditContents