python lambda – Part 1

En Python, una función anónima significa que una función no tiene nombre. Como ya sabemos, la palabra clave def se usa para definir las funciones normales y la palabra clave lambda se usa para crear funciones anónimas.

Sintaxis:

Python3

# Python program to demonstrate
# lambda functions
 
 
string = 'GeeksforGeeks'
 
# lambda returns a function object
print(lambda string: string)

Python3

# Python program to demonstrate
# lambda functions
 
 
x = "GeeksforGeeks"
 
# lambda gets pass to print
(lambda x: print(x))(x)

Python3

# Python program to illustrate cube of a number
# showing difference between def() and lambda().
 
 
def cube(y):
    return y*y*y
 
 
def g(x): return x*x*x
 
 
print(g(7))
 
print(cube(5))

Python3

# Python program to demonstrate
# lambda functions
 
 
def power(n):
    return lambda a: a ** n
 
 
# base = lambda a : a**2 get
# returned to base
base = power(2)
 
print("Now power is set to 2")
 
# when calling base it gets
# executed with already set with 2
print("8 powerof 2 = ", base(8))
 
# base = lambda a : a**5 get
# returned to base
base = power(5)
print("Now power is set to 5")
 
# when calling base it gets executed
# with already set with newly 2
print("8 powerof 5 = ", base(8))

Python3

# Python program to demonstrate
# lambda functions inside map()
# and filter()
 
 
a = [100, 2, 8, 60, 5, 4, 3, 31, 10, 11]
 
# in filter either we use assignment or
# conditional operator, the pass actual
# parameter will get return
filtered = filter (lambda x: x % 2 == 0, a)
print(list(filtered))
 
# in map either we use assignment or
# conditional operator, the result of
# the value will get returned
mapped = map (lambda x: x % 2 == 0, a)
print(list(mapped))

Publicación traducida automáticamente

Artículo escrito por Tejashwi5 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *