>>> def func(x, y, z): return x + y + z
...
>>> func(2, 3, 4)
9



>>> f = lambda x, y, z: x + y + z
>>> f(2, 3, 4)
9



>>> x = (lambda a="fee", b="fie", c="foe": a + b + c)
>>> x("wee")
'weefiefoe'



>>> def knights():
...     title = 'Sir'
...     action = (lambda x: title + ' ' + x)   # Title in enclosing def
...     return action                          # Return a function.
...
>>> act = knights()
>>> act('robin')
'Sir robin'



L = [(lambda x: x**2), (lambda x: x**3), (lambda x: x**4)]

for f in L:
    print f(2)     # Prints 4, 8, 16

print L[0](3)      # Prints 9



>>> key = 'got'
>>> {'already': (lambda: 2 + 2),
...  'got':     (lambda: 2 * 4),
...  'one':     (lambda: 2 ** 6)
... }[key]()
8



def f1(): return 2 + 2
def f2(): return 2 * 4
def f3(): return 2 ** 6
...

key = 'one'
{'already': f1, 'got': f2, 'one': f3}[key]()



if a:
    b
else:
    c

b if a else c

((a and b) or c)



>>> lower = (lambda x, y: x if x < y else y)
>>> lower('bb', 'aa')
'aa'
>>> lower('aa', 'bb')
'aa'



>>> import sys
>>> showall = (lambda x: map(sys.stdout.write, x))

>>> t = showall(['spam\n', 'toast\n', 'eggs\n'])
spam
toast
eggs

>>> showall = lambda x: [sys.stdout.write(line) for line in x]

>>> t = showall(('bright\n', 'side\n', 'of\n', 'life\n'))
bright
side
of
life 



>>> def action(x):
...     return (lambda y: x + y)        # Make and return function, remember x.

>>> act = action(99)
>>> act
<function <lambda> at 0x00A16A88>
>>> act(2)
101



>>> action = (lambda x: (lambda y: x + y))
>>> act = action(99)
>>> act(3)
102
>>> ((lambda x: (lambda y: x + y))(99))(4)
103



import sys
x = Button(
        text ='Press me',
        command=(lambda:sys.stdout.write('Spam\n')))



class MyGui:
    def makewidgets(self):
        Button(command=(lambda: self.display("spam")))
    def display(self, message):
        ...use message...



>>> def func(x, y, z): return x + y + z
...
>>> apply(func, (2, 3, 4))
9
>>> f = lambda x, y, z: x + y + z
>>> apply(f, (2, 3, 4))
9



if <test>:
    action, args = func1, (1,)
else:
    action, args = func2, (1, 2, 3)
. . . 
apply(action, args)



>>> args = (2,3) + (4,)
>>> args
(2, 3, 4)
>>> apply(func, args)
9



>>> def echo(*args, **kwargs): print args, kwargs

>>> echo(1, 2, a=3, b=4)
(1, 2) {'a': 3, 'b': 4}



>>> pargs = (1, 2)
>>> kargs = {'a':3, 'b':4}
>>> apply(echo, pargs, kargs)
(1, 2) {'a': 3, 'b': 4}



>>> apply(func, args)              # Traditional: tuple
9
>>> func(*args)                    # New apply-like syntax
9
>>> echo(*pargs, **kargs)          # Keyword dictionaries too
(1, 2) {'a': 3, 'b': 4}



>>> echo(0, *pargs, **kargs)       # Normal, *tuple, **dictionary
(0, 1, 2) {'a': 3, 'b': 4}



>>> counters = [1, 2, 3, 4]
>>>
>>> updated = []
>>> for x in counters:
...     updated.append(x + 10)              # Add 10 to each item.
...
>>> updated
[11, 12, 13, 14]



>>> def inc(x): return x + 10               # function to be run
...
>>> map(inc, counters)                      # Collect results.
[11, 12, 13, 14]



>>> map((lambda x: x + 3), counters)        # Function expression
[4, 5, 6, 7]



>>> def mymap(func, seq):
...     res = []
...     for x in seq: res.append(func(x))
...     return res
...
>>> map(inc, [1, 2, 3])
[11, 12, 13]
>>> mymap(inc, [1, 2, 3])
[11, 12, 13]



>>> pow(3, 4)
81
>>> map(pow, [1, 2, 3], [2, 3, 4])       # 1**2, 2**3, 3**4
[1, 8, 81]



>>> range(-5, 5)
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]

>>> filter((lambda x: x > 0), range(-5, 5))
[1, 2, 3, 4]



>>> res = []
>>> for x in range(-5, 5):
...     if x > 0:
...         res.append(x)
...
>>> res
[1, 2, 3, 4]



>>> reduce((lambda x, y: x + y), [1, 2, 3, 4])
10
>>> reduce((lambda x, y: x * y), [1, 2, 3, 4])
24



>>> L = [1,2,3,4]
>>> res = L[0]
>>> for x in L[1:]:
...     res = res + x
...
>>> res
10



>>> def myreduce(function, sequence):
        tally = sequence[0]
        for next in sequence[1:]:
            tally = function(tally, next)
        return tally

>>> myreduce((lambda x, y: x + y), [1, 2, 3, 4, 5])
15
>>> myreduce((lambda x, y: x * y), [1, 2, 3, 4, 5])
120



>>> import operator
>>> reduce(operator.add, [2, 4, 6])      # function-based +
12
>>> reduce((lambda x, y: x + y), [2, 4, 6])
12



>>> ord('s')
115



>>> res = []
>>> for x in 'spam': 
...     res.append(ord(x))
...
>>> res
[115, 112, 97, 109]



>>> res = map(ord, 'spam')               # Apply function to sequence.
>>> res
[115, 112, 97, 109]



>>> res = [ord(x) for x in 'spam']       # Apply expression to sequence.
>>> res
[115, 112, 97, 109]



>>> [x ** 2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]



>>> map((lambda x: x ** 2), range(10))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]



>>> [x for x in range(5) if x % 2 == 0]
[0, 2, 4]

>>> filter((lambda x: x % 2 == 0), range(5))
[0, 2, 4]

>>> res = [  ]
>>> for x in range(5):
...     if x % 2 == 0: 
...         res.append(x)
...        
>>> res
[0, 2, 4]



>>> [x ** 2 for x in range(10) if x % 2 == 0]
[0, 4, 16, 36, 64]



>>> map((lambda x: x**2), filter((lambda x: x % 2 == 0), range(10)))
[0, 4, 16, 36, 64]



 [ expression for target1 in sequence1 [if condition]
             for target2 in sequence2 [if condition] ...
             for targetN in sequenceN [if condition] ]



>>> res = [x + y for x in [0, 1, 2] for y in [100, 200, 300]]
>>> res
[100, 200, 300, 101, 201, 301, 102, 202, 302]



>>> res = []
>>> for x in [0, 1, 2]:
...     for y in [100, 200, 300]:
...         res.append(x + y)
...
>>> res
[100, 200, 300, 101, 201, 301, 102, 202, 302]



>>> [x + y for x in 'spam' for y in 'SPAM']
['sS', 'sP', 'sA', 'sM', 'pS', 'pP', 'pA', 'pM', 
'aS', 'aP', 'aA', 'aM', 'mS', 'mP', 'mA', 'mM']



>>> [(x, y) for x in range(5) if x % 2 == 0 for y in range(5) if y % 2 == 1]
[(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]



>>> res = []
>>> for x in range(5):
...     if x % 2 == 0:
...         for y in range(5):
...             if y % 2 == 1:
...                 res.append((x, y))
...
>>> res
[(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]



>>> M = [[1, 2, 3],
         [4, 5, 6],
         [7, 8, 9]]
 
>>> N = [[2, 2, 2],
         [3, 3, 3],
         [4, 4, 4]]



>>> M[1]
[4, 5, 6]

>>> M[1][2]
6



>>> [row[1] for row in M]
[2, 5, 8]

>>> [M[row][1] for row in (0, 1, 2)]
[2, 5, 8]



>>> [M[i][i] for i in range(len(M))]
[1, 5, 9]



>>> [M[row][col] * N[row][col] for row in range(3) for col in range(3)]
[2, 4, 6, 12, 15, 18, 28, 32, 36] 

>>> [[M[row][col] * N[row][col] for col in range(3)] for row in range(3)]
[[2, 4, 6], [12, 15, 18], [28, 32, 36]]



>>> res = []
>>> for row in range(3):
        tmp = []
        for col in range(3):
            tmp.append(M[row][col] * N[row][col])
        res.append(tmp)
	
>>> res
[[2, 4, 6], [12, 15, 18], [28, 32, 36]]



>>> open('myfile').readlines()
['aaa\n', 'bbb\n', 'ccc\n']

>>> [line.rstrip() for line in open('myfile').readlines()]
['aaa', 'bbb', 'ccc']

>>> [line.rstrip() for line in open('myfile')]
['aaa', 'bbb', 'ccc']

>>> map((lambda line: line.rstrip()), open('myfile'))
['aaa', 'bbb', 'ccc']



listoftuple = [('bob', 35, 'mgr'), ('mel', 40, 'dev')]

>>> [age for (name, age, job) in listoftuple]
[35, 40]

>>> map((lambda (name, age, job): age), listoftuple)
[35, 40]



>>> def gensquares(N):
...     for i in range(N):
...         yield i ** 2               # Resume here later.



>>> for i in gensquares(5):        # Resume the function. 
...     print i, ':',              # Print last yielded value.
...
0 : 1 : 4 : 9 : 16 :
>>>



>>> x = gensquares(4)
>>> x
<generator object at 0x0086C378>



>>> x.next()
0
>>> x.next()
1
>>> x.next()
4
>>> x.next()
9
>>> x.next()

Traceback (most recent call last):
  File "<pyshell#453>", line 1, in <module>
    x.next()
StopIteration



>>> def buildsquares(n):
...     res = []
...     for i in range(n): res.append(i**2)
...     return res
...
>>> for x in buildsquares(5): print x, ':',
...
0 : 1 : 4 : 9 : 16 :




>>> for x in [n**2 for n in range(5)]:
...     print x, ':',
...
0 : 1 : 4 : 9 : 16 :

>>> for x in map((lambda x:x**2), range(5)):
...     print x, ':',
...
0 : 1 : 4 : 9 : 16 :



>>> D = {'a':1, 'b':2, 'c':3}
>>> x = iter(D)
>>> x.next()
'a'
>>> x.next()
'c'



>>> for key in D: 
...     print key, D[key]
...
a 1
c 3
b 2



>>> for line in open('temp.txt'):
...     print line,
...
Tis but
a flesh wound.



>>> [x ** 2 for x in range(4)]      # list comprehension: build a list
[0, 1, 4, 9]
 
>>> (x ** 2 for x in range(4))      # generator expression: make an iteratable
<generator object at 0x011DC648>



>>> G = (x ** 2 for x in range(4))
>>> G.next()
0
>>> G.next()
1
>>> G.next()
4
>>> G.next()
9
>>> G.next()

Traceback (most recent call last):
  File "<pyshell#410>", line 1, in <module>
    G.next()
StopIteration



>>> for num in (x ** 2 for x in range(4)):
        print '%s, %s' % (num, num / 2.0)

0, 0.0
1, 0.5
4, 2.0
9, 4.5


>>> sum(x ** 2 for x in range(4))
14

>>> sorted(x ** 2 for x in range(4))
[0, 1, 4, 9]

>>> sorted((x ** 2 for x in range(4)), reverse=True)
[9, 4, 1, 0]

>>> import math
>>> map(math.sqrt, (x ** 2 for x in range(4)))
[0.0, 1.0, 2.0, 3.0]



# file timerseqs.py

import time, sys
reps = 1000
size = 10000

def tester(func, *args):
    startTime = time.time()
    for i in range(reps):
        func(*args)
    elapsed = time.time() - startTime
    return elapsed

def forStatement():
    res = []
    for x in range(size):
        res.append(abs(x))

def listComprehension():
    res = [abs(x) for x in range(size)]

def mapFunction():
    res = map(abs, range(size))

def generatorExpression():
    res = list(abs(x) for x in range(size))

print sys.version
tests = (forStatement, listComprehension, mapFunction, generatorExpression)
for testfunc in tests:
    print testfunc.__name__.ljust(20), '=>', tester(testfunc) 



2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)]
forStatement         => 6.10899996758
listComprehension    => 3.51499986649
mapFunction          => 2.73399996758
generatorExpression  => 4.11600017548





def forStatement():
    res = []
    for x in range(size):
        res.append(x + 10)

def listComprehension():
    res = [x + 10 for x in range(size)]

def mapFunction():
    res = map((lambda x: x + 10), range(size))

def generatorExpression():
    res = list(x + 10 for x in range(size))





2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)]
forStatement         => 5.25699996948
listComprehension    => 2.68400001526
mapFunction          => 5.96900010109
generatorExpression  => 3.37400007248



>>> def echo(message):           # Echo assigned to a function object.
...     print message
...
>>> x = echo                     # Now x references it too.
>>> x('Hello world!')            # Call the object by adding ().
Hello world!



>>> def indirect(func, arg):
...     func(arg)                         # Call the object by adding ().
...
>>> indirect(echo, 'Hello jello!')        # Pass function to a function.
Hello jello!



>>> schedule = [ (echo, 'Spam!'), (echo, 'Ham!') ]
>>> for (func, arg) in schedule:
...     func(arg)
...
Spam!
Ham!



>>> X = 99
>>> def selector():        # X used but not assigned
...     print X              # X found in global scope
...
>>> selector()
99



>>> def selector():
...     print X              # Does not yet exist!
...     X = 88               # X classified as a local name (everywhere)
...                          # Can also happen if "import X", "def X",...
>>> selector()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in selector
UnboundLocalError: local variable 'X' referenced before assignment



>>> def selector():
...     global X           # Force X to be global (everywhere).
...     print X
...     X = 88
...
>>> selector()
99



>>> X = 99
>>> def selector():
...     import __main__     # Import enclosing module.
...     print __main__.X    # Qualify to get to global version of name.
...     X = 88                  # Unqualified X classified as local.
...     print X                 # Prints local version of name.
...
>>> selector()
99
88



>>> def saver(x=[]):            # Saves away a list object
...     x.append(1)             # Changes same object each time!
...     print x
...
>>> saver([2])                  # Default not used
[2, 1]
>>> saver()                   # Default used
[1]
>>> saver()                   # Grows on each call!
[1, 1]
>>> saver()
[1, 1, 1]



>>> def saver(x=None):
...     if x is None:         # No argument passed?
...         x = []            # Run code to make a new list.
...     x.append(1)           # Changes new list object
...     print x
...
>>> saver([2])
[2, 1]
>>> saver()                   # Doesn't grow here
[1]
>>> saver()
[1]



>>> def proc(x):
...     print x        # No return is a None return.
...
>>> x = proc('testing 123...')
testing 123...
>>> print x
None



>>> list = [1, 2, 3]
>>> list = list.append(4)      # append is a "procedure."
>>> print list                 # append changes list in-place. 
None



def f1(a, b): print a, b             # Normal args

def f2(a, *b): print a, b            # Positional varargs

def f3(a, **b): print a, b           # Keyword varargs

def f4(a, *b, **c): print a, b, c    # Mixed modes

def f5(a, b=2, c=3): print a, b, c   # Defaults

def f6(a, b=2, *c): print a, b, c    # Defaults and positional varargs

>>> f1(1, 2)                  
>>> f1(b=2, a=1)              

>>> f2(1, 2, 3)               
>>> f3(1, x=2, y=3)           
>>> f4(1, 2, 3, x=2, y=3)     

>>> f5(1)                    
>>> f5(1, 4)                 

>>> f6(1)                    
>>> f6(1, 3, 4)



x = y / 2                          # For some y > 1
while x > 1:
    if y % x == 0:                 # Remainder
        print y, 'has factor', x
        break                      # Skip else
    x = x-1
else:                              # Normal exit
    print y, 'is prime'

