Python and Python bites “lambda”

pythonbite

 

 Hi everyone, this article show you one powerful function in Python programming language called “lambda”. It can solve any small problem in single line code. So lets start the beginning of your interesting or may be future programming language.

Anonymous functions created at runtime are known as lambda functions. The below line defines an ordinary function usage in python.

>>def f (x): return x+42
>>print f(21)
63

For lambda functions,
>>calc = lambda x: x+42
>>calc(21)
63

 

lambda definition does not include a “return” statement. It always contains an expression which is returned. Also you can put a lambda definition anywhere a function is expected, and you don’t have to assign it to a variable at all.

Let’s take it a little further. . .

First we define a simple list of integer values, then we use the standard functionsfilter(), map() and reduce() to do various things with that list.

All of the three functions expect two arguments:

We can simply add lambda functions instead of functions to save our time to filter data

>>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
>>> print filter(lambda x: x % 3 == 0, foo)
[18, 9, 24, 12, 27]

>>> print map(lambda x: x * 2 + 10, foo)

[14, 46, 28, 54, 44, 58, 26, 34, 64]

 

>>> print reduce(lambda x, y: x + y, foo)
139
Another example given below is to compute prime numbers in Python

>>> nums = range(2, 50)
>>> for i in range(2, 8):
… nums = filter(lambda x: x == i or x % i, nums)

>>> print nums
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

 

Let’s get into applications:

In UNIX,We want to find all mount points in our file system. To do that, we execute the external “mount” command and parse the output.

>>> import commands
>>>
>>> mount = commands.getoutput(‘mount -v’)
>>> lines = mount.splitlines()
>>> points = map(lambda line: line.split()[2], lines)
>>>
>>> print points
[‘/’, ‘/var’, ‘/usr’, ‘/usr/local’, ‘/tmp’, ‘/proc’]

Lets make it even efficient….

print map(lambda x: x.split()[2], commands.getoutput(‘mount -v’).splitlines()) [‘/’, ‘/var’, ‘/usr’, ‘/usr/local’, ‘/tmp’, ‘/proc’]
So Using lambda functions makes programs more efficient and more user-friendly. .

go to https://www.linkedin.com/pulse/python-bites-mukesh-kumar?trk=mp-reader-card

Leave a Reply

Your email address will not be published. Required fields are marked *