Introduction to lambda functions in Python

A quick introduction to lambda functions in Python.

Below you find some examples of lambda functions in Python.

Documentation is added to the code directly – in the form of comments.

Lambda fucntions in Python are stated in accordance with the following syntax: lamda arguments : expression

# defining functions "cubing" with lambda operator
cubing = lambda x: x**3

# let us test function on a numpy array
import numpy
cubing(numpy.array([1,2,3]))
array([ 1,  8, 27], dtype=int32)
# defining function summing, for summing to arguments
summing = lambda x,y: x + y

# let us test summing on two numpy arrays of same length
summing(numpy.array([1,2,3]),
        numpy.array([7,9,12]))
array([ 8, 11, 15])
# we can also explicitly mention the parameters when calling the function
summing(x = numpy.array([1,2,3]),
       y = numpy.array([7,9,12]))
array([ 8, 11, 15])
# lambda functions can have a return value, as seen above;
# however, they must not return anything; see below
printingSomething = lambda : print("something")
printingSomething()
something
# lambda functions work with abstract datatypes, i.e. customized classes, too
class Person:
    # constructor method
    def __init__(self,name,age):
        self.name = name
        self.age = age
    # method for printing personal info
    def printInfo(self):
        print(self.name + " has age: " + str(self.age))
# defining a function with lambda operator
listingObjects = lambda x,y,z: [x,y,z]
# testing lambda function on 3 person objects
persons = listingObjects(x = Person(name = "Lisa", age = 22),
               y = Person(name = "John", age = 65),
               z = Person(name = "Charles", age = 54))
for i in persons:
    i.printInfo()
Lisa has age: 22
John has age: 65
Charles has age: 54

You May Also Like

Leave a Reply

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.