Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- listOfNumbers = [1,2,3,4,5]
- square = lambda x: x * x
- listOfLambdas = [lambda: square(i) for i in listOfNumbers]
- for f in listOfLambdas:
- print f(),
- 1 4 9 16 25
- 25 25 25 25 25
- listOfLambdas = []
- for num in listOfNumbers:
- action = lambda: square(num)
- listOfLambdas.append(action)
- print action()
- for f in listOfLambdas:
- print f(),
- def square(x): return lambda : x*x
- listOfLambdas = [square(i) for i in [1,2,3,4,5]]
- for f in listOfLambdas: print f()
- 1
- 4
- 9
- 16
- 25
- listOfLambdas = [lambda: i*i for i in range(6)]
- for f in listOfLambdas:
- print f()
- 25
- 25
- 25
- 25
- 25
- 25
- listOfLambdas = [lambda i=i: i*i for i in range(6)]
- for f in listOfLambdas:
- print f()
- 0
- 1
- 4
- 9
- 16
- 25
- listOfLambdas = [lambda i=i: square(i) for i in listOfNumbers]
- listOfLambdas = map(lambda i: lambda: square(i), listOfNumbers)
- for num in range(1, 6):
- pass
- assert num == 5 # num is now bound in the enclosing scope
- for num in range(1, 6):
- spam = 12
- assert num == 5 # num is now bound in the enclosing scope
- assert spam == 12 # spam is also bound in the enclosing scope
- [num for num in range(1, 6)]
- assert num == 5
- functions = []
- for number in range(1, 6):
- def fun():
- return number
- functions.append(fun)
- assert all(fun() == 5 for fun in functions)
- assert all(fun() is number for fun in functions)
- # Same as above -- commented out for emphasis.
- #functions = []
- #for number in range(1, 6):
- # def fun():
- # return number
- # functions.append(fun)
- #assert all(fun() == 5 for fun in functions)
- #assert all(fun() is number for fun in functions)
- number = 6 # Rebind 6 in the scope and see how it affects the results.
- assert all(fun() == 6 for fun in functions)
- def get_fun(value):
- """:return: A function that returns :param:`value`."""
- def fun(): # Bound to get_fun's scope
- return value
- return fun
- functions = []
- for number in range(1, 6):
- functions.append(get_fun(number))
- assert [fun() for fun in functions] == range(1, 6)
- # Same as before, commented out for emphasis.
- #functions = []
- #for number in range(1, 6):
- # functions.append(get_fun(number))
- #assert [fun() for fun in functions] == range(1, 6)
- print functions[0].__closure__
- # Produces: (<cell at 0x8dc30: int object at 0x1004188>,)
- >>> class square(object):
- ... def __init__(self, val):
- ... self.val = val
- ... def __call__(self):
- ... return self.val * self.val
- ...
- >>> l = [1,2,3,4,5]
- >>> funcs = [square(i) for i in l]
- >>> for f in funcs:
- ... print f()
- ...
- 1
- 4
- 9
- 16
- 25
- >>>
Add Comment
Please, Sign In to add comment