Lambda:
In the below example you can see two methods have been created and clearly explained to show how Lambda works
friends = [
{"name": "Ram", "age":26},
{"name": "Raju", "age":30}
]
#method with for loop
def findAge(name):
for friend in friends:
if(friend["name"] == name):
return friend
return f"{name} not found"
#method with Lambda expression
def findAgeLambda(name):
friend = next(filter(lambda x: x["name"] == name, friends))
return friend
print(findAge("Ram"))
print(findAgeLambda("Raju"))
Output:
{'name': 'Ram', 'age': 26}
{'name': 'Raju', 'age': 30}
No comments:
Post a Comment