Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Tuesday, 30 March 2021

Lambda Function in Python

 

Lambda Function

Lambda function is a function, which is defined without a name (anonymous). Hence, named as anonymous function. Lambda function is defined using the keyword lambda that’s why it also called as lambda function.

Lambda functions are syntactically restricted to a single expression. However, can have multiple arguments separated with commas. Semantically, lambda functions are just syntactic sugar for a normal function definition. Lambda functions can be used wherever function objects are required.

 

Using lambda function

syntax- lambda args: expression

pow = lambda x: x**2

print(pow(2))


Here, x is the argument to the lambda function and x**2 is the expression which gets assigned to the variable ”pow” after evaluation. 

Notice, the lambda function has no name and doesn’t contain any parentheses unlike normal function.

The above lambda function is similar to:

def pow(x):

    return x**2

 

 

 

Saturday, 20 March 2021

ChainMap in Python

 

ChainMap is used to group multiple dicts together to create a single view. It is present in Collections module.

The underlying dictionaries or mappings are stored in a list. This list can accessed using the maps attribute.

Required Key is searched through all the mappings or dictionaries in the ChainMap until it is found. Raises KeyError if the key is not found in any of the mappings.

 

Creating ChainMap

ChainMap can be created using built-in ChainMap( ) function:

from collections import ChainMap

d1 = {"a":1, "b":2,"c":3}

d2 = {"b":5,"d":6}

chainMap = ChainMap(d1, d2)

print(chainMap)

 


Write, update and delete operations only operate on first mapping. Consider the below code:

from collections import ChainMap

d1 = {"a":1, "b":2,"c":3}

d2 = {"b":5,"d":6}

chainMap = ChainMap(d1, d2)

chainMap["b"] = 4

print(chainMap.maps)

 

 

Trying to update the value of the existing key in the dict other than first dict in the ChainMap results in creating new key-value in the first dict as shown below:

from collections import ChainMap

d1 = {"a":1, "b":2,"c":3}

d2 = {"b":5,"d":6}

chainMap = ChainMap(d1, d2)

chainMap["d"] = 4

print(chainMap.maps)

 

Because ChainMap doesn’t allow update, write and delete operations on dicts ohter than first dict.