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...

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...

Python Hunter, Post on Python Tuple.

Tuple is like list but unlike in structure and functionality. first basic difference is can be figured out by the structure. List elements are enclosed with '[]' brackets but tuple elements are enclosed with '()' parentheses. Few properties of tuple:- 1. It is faster than list. 2. Unlike list, tuple is immutable, i.e. tuple's data cannot be changed once created, we should use tuple if we want our data to be safe from accidental change.  As you can see in title picture, you are allowed to see but cannot touch it. 3. We can use tuple as key in dictionaries   whereas this is not the case with list,  we can’t use list as key in dictionary <Link this post (dictionary) will be available on 16 March 2018>.      Examples:-  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 myTuple= tuple ( 'Python' ) # it takes only one parameter print (myTuple) #it will break down each character into separate elements, just l...