Python

Def

def apply(f, n):
*# Part 3: invoke the lambda.*
result = f(n)
print(*"RESULT:"*, result)
*# Part 1: create 2 similar lambdas.*
square = **lambda** n: n * n
cube = **lambda** n: n * n * n
*# Part 2: pass lambdas to apply method.*
apply(square, 4)
apply(cube, 3)RESULT: 16
RESULT: 27

None

Console, print

add_two = lambda n: *n + 2*
multiply_add_two = lambda n: add_two(*n * 2*) *# Call lambda in lambda.*
print(multiply_add_two(*3*))
print(multiply_add_two(*5*))8
12

line1 = *"A cat, a dog "*
line2 = *" a bird, a mountain"*
*# Use X as an alias for two methods.*
x = **lambda** s: s.strip().upper()
*# Call the lambda to shorten the program's source.*
line1b = x(line1)
line2b = x(line2)
print(line1b)
print(line2b)A CAT, A DOG
A BIRD, A MOUNTAIN

import math
values = [10, 20, 30]
*# Apply sqrt to all elements in the list with map.*
result1 = **map**(math.sqrt, values)
*# We can use a lambda, but it is not needed.*
result2 = **map**(lambda x: math.sqrt(x), values)
print(*"values:"*, values)
print(*"math.sqrt:"*, list(result1))
print(*"lambda:"*, list(result2))values: [10, 20, 30]
math.sqrt: [3.1622776601683795, 4.47213595499958, 5.477225575051661]
lambda: [3.1622776601683795, 4.47213595499958, 5.477225575051661]

import time
*# Method.*
def square1(n):
return n ** 2
*# Lambda method.*
square2 = **lambda** n: n ** 2
print(time.time())
*# Version 1: use def method.*
i = 0
**while** i < 10000000:
square1(1)
i += 1
print(time.time())
*# Version 2: use lambda method.*
i = 0
**while** i < 10000000:
square2(1)
i += 1
print(time.time())1346613154.399
1346613158.919 (Def = *4.52 s*)
1346613163.397 (Lambda = *4.48 s*)

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

This page was last updated on Jun 1, 2023 (edit).