Skip to main content

Understand the lambda expression python. On Python Hunter


hitman47silent994c4@gmail.com
Hello and welcome again.

If you are reading this blog then surely you are having some difficulties to understand lambda in python.


Well, no need to feel down, it happens to every beginner as i also have been through this.



Let's understand the lambda expression.

 Follow Python Hunter on youtube   Follow Python Hunter on twitter Follow on tumbl ( at your own risk ) check profile on linkedIn 


Anonymous functions can be created with lambda expression, commonly known as lambda functions or anonymous functions. 



Lambda expression gives us the facility to write very short function in one expression.



Here are some examples that will help you to comprehend the lambda expression. (Just for beginner)


this picture shows the different parts of lambda expression.

NOTE: Every code snippet is tested in python version 3.x

Lambda expression without any argument.
method = lambda : 1+3 # or any other expression.
print(method())

Output:- 4

If you print what type of variable is that

print(type(method))

It will print <class 'function'>

Just like that:
def method():
    return 1+3;

Lambda expression that receives simple arguments.

method=lambda arg1,arg2,so_on: print(arg1,' ',arg2,' ',so_on)
print(method('','',''))

Output:- None

The above code is calling the method("","","") with three blank args it will print nothing

method("Hello ","Mr.","Python Hunter")

The above code is calling the method() with three args it will print "Hello Mr. Python Hunter"

The above lambda expression 
lambda arg1,arg2,so_on: print(arg1,'',arg2,'',so_on) 
is simillar to:

def method(arg1,arg2,so_on):
    print(arg1,'',arg2,'',so_on)

Instead of using def keyword and defining a python function, lambda comes handy to make short functions in single line.

Lambda expression that receives varargs (variable arguments).

method=lambda *a:[x for x in a]
print(method(1,2,4,5,6))

The above lambda expression to receive varargs.
Just like below:

def method(*a):
for i in a:
print(i)
method(1,2,3,4,5,6)

Note:- Make sure the indention.
Now you see the difference, it took 3 lines to define a function but with lambda expression it took only one line.
This approach will come handy when you will be expert in python and want to save time while writing big codes.

Lambda expression that receives kargs (keyword arguments).

method=lambda **Karg:[Karg[x] for x in Karg]
print(type(method))
print(method(arg1="q",arg2="w",arg3="e"))

Just like below:
def method(**a):
for i in a:
print(a[i],i)


Using if else conditions in lambda expression.

The below code will prompt the user to enter a number and test it whether it is ever or odd.
Note below example works fine in python version 2.7
number = lambda T: str(T)+" is even" if T%2==0 else str(T)+" is odd"
x=input("Enter Number to check whether it is ever or odd: ")

print(number(x))

otherwise we have to write the following code:

def number(T):
    if(T%2==0):
        print(str(T)+ " is even")
    else:
        print(str(T)+ " is odd")
x=input()
number(x)

Limitation:
  1. You can not make any comment in lambda expression.
  2. You can not declare and assign value to any variable in lambda expression.
  3. You can not declare return any variable in lambda expression.
  4. You can not declare multiple statements in lambda expression.
i'm also a beginner and exploring python, and its my right to share the knowledge and i'm doing my best.
And please carry out some experiments on lambda expression to comprehend it to large extent.
And if you find anything peculiar, please drop an email to hitman47silent994c4@gmail.com 
because the adage says 
Knowledge multiplies when shared. ☺
For beginner this post is helpful to understand the lambda expression, lambda expression is not a BIG GUN or huge topic it self.
But for further exploration please visit here http://www.python-course.eu/lambda.php .

Comments

Post a Comment

Thanks in anticipation.

Popular posts from this blog

Understanding the usage of underscore( _ ) of Python for beginner. On Python Hunter

Introduction: Just like you, a newbie in python scripting language, me too was confused about lot of new things in python that are not valid or available in other languages like Java, .Net etc. Just like other things i had seen the use of '_' underscore in python, at beginning level that flabbergasted me for a while.      With some research and practice i have summarised the following usage of '_' underscore in python. Hope you will find it helpful at beginning level. First Usage : Hold the previous output value. When used in interpreter. 1 2 3 4 5 6 7 _ = input () # For example you typed '5' print (_) # This will print '5' print ( int ( _ ) * int ( _ ) ) # This will print '25' print ( int ( _ ) + 10 ) The above will print '15', because last input was "5" and in above   line of code is producing '25' as output but not being handl

XSLT apply import tag by pran sukh on python hunter blog

Modular Programming is good attitude of best programmer. We often need to keep our code in modular approach so that is would be easy to maintain  and update or remove dead code and also it ease the process of bug tracking. XML and XSL  processors provide freedom to import multiple imports to process the same  XML  document. In the following  XML  data we have data from collage where student's and teacher's data is given. But we want to process the same  XML  data with different XSL files. Here in this example we want to show the teacher data in red background color and student data in green background color. Data.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 <?xml version = "1.0"?> <?xml-stylesheet type = "text/xsl" href = "RootXSLT.xsl"?> <data> <DataFor name = "Student" id = "001" > <firstname>

Understanding "with" keyword in python, on Python Hunter

J ust like anything in python, keyword "with" is introduced in python to make the things little easy. Imagine a situation where you have to manage the resources e.g opening file and closing them after the code is executed on file. To achieve this sort of task we have to write the code as follow:      Download   But if you do it often you could do this as follow to make the code reusable: Download But why do you need to do this when you know that you have to execute the only for once.  To answer this question  python-dev team finally came up with following approach: Download  Note:- Make sure you have "file.txt" and python code file in same dir. The "with"  keyword replaces the try finally block. "with" keyword executes the openFileClass() context manager and internally calls the __enter__(self) method, and whatever is being returned from __enter__(self) method is being stored in tar