Lambda Expressions in Python 3

In Python 3, Lambda Expressions are supported. Like Java 8, they are anonymous functions, which are very handy. They mix simplicity with readability and reusability. Their functional programming style makes them handy for writing conditional and mathematical expressions.

Java 8

list.forEach(a -> {

System.out.println(Math.sqrt(a));

}

Python on the other hand defines lambdas in a different way.

object = lambda identifier : identifier

object = lambda identifier : iif identifier == someVariable

As emphasised above, we need to specify the lambda keyword. We provide an identifier (this can be a String/List/Integer/Float/Double or even an object); this is our input variable. You can define multiple identifiers. It provides us the ability to define an expression or operation we want to perform on the identifier(s). The semi-colon (:) allows us to do this. object just denotes an object which contains our lambda function. We can call the Lambda like so:

object(45)

Here’s a simple and better implementation of a Lambda:

even = lambda num : num % 2
print(even(45)) # prints 1, which is odd

Try it online: https://repl.it/languages/python3

This entry was posted in Python, Software Engineering. Bookmark the permalink. Follow any comments here with the RSS feed for this post. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>