What Are Python Lambdas?

What Are Python Lambdas?

Hi Pythonista 👋, welcome to my blog today and we shall get to understand what Lambda functions are from a basic level and see basic use cases, whys and why not. Sit tight!

Lambda Defined ✔

Lambda Function in Python programming is an anonymous function or a function having no name. It is a small and restricted function having no more than one line. Just like a normal function, a Lambda function can have multiple arguments with one expression.

image.png
Python and other languages like Java, C#, and even C++ have had lambda functions added to their syntax, whereas languages like LISP or the ML family of languages, Haskell, OCaml, and F#, use lambdas as a core concept.

A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.

A Python lambda function behaves like a normal function in regard to arguments.

Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code.

History & Introduction In Python

Lambda expressions in Python and other programming languages have their roots in lambda calculus, a model of computation invented by Alonzo Church.

image.png
Python is not inherently a functional language, but it adopted some functional concepts early on. In January 1994, map() , filter() , reduce() , and the lambda operator were added to the language.

🔹Declaration & Syntax of Lambda Function in Python:

While normal functions are defined using the def keyword, anonymous functions are defined using the lambda keyword. However, they are restricted to a single line of expression.

They can take in multiple parameters as in regular functions.

lambda arguments: expression

Normal Function

def example(m):
    return m

example() takes an argument m and returns it upon invocation.

lambda m: m

As you can see above, a lambda expression is a way of creating a little function inline, without all the syntax of a def. In the example above, the expression is composed of:

🔹The keyword: lambda
🔹A bound variable: m
🔹A body: m

Lambda functions are used when you need a function for a short period of time.
Example to triple a number!

triple = lambda x: x*3

We can now get the output by passing in 10 to return 30.

print(triple(10))

This is commonly used when you want to pass a function as an argument to higher-order functions, that is, functions that take other functions as their arguments. Let's see these examples.

🔸 lambda with filter()

# Assume Students Marks
marks = [100,25,80,70,55,40,30,11,30,60]

# Use Filter & Lambda to get those above 55 (Average)
filtered_answer = filter(lambda x: x > 55, marks)

# Turn a filter object into a list
above_55 = list(filtered_answer)

# Get the pass list
print(f"They are only {len(above_55)} above 55!")

Read Comments to understand, you can also read about filter() from here .

🔸 lambda with map()

# Assume temperatures in C
C = [39.2, 36.5, 37.3, 38, 37.8]

# A lambda function to convert to F
convert = lambda x: (float(9)/5)*x + 32

# Map() maps our convert unto C temps
F = map(convert, C)

# Return our list-from a map object
print(list(F))

Read comments for explanation & map() from here

🔸 lambda with reduce()

Python's reduce() was originally a built-in function but it was moved to functools.

# Import reduce
from functools import reduce

# calculating sum
sum_ = lambda x, y: x+y

# map our sum unto reduce() with a range()
sum_1_to_100 = reduce(sum_, range(1,101))

#reduce returns int by default not an object
print(sum_1_to_100)

Read comments for explanation & map() from here!

Points To Note 🖍

📌 It is written as a single line of execution.
📌 It does not support type annotations.
📌 It can be immediately invoked (IIFE).
📌 A lambda function can’t contain any statements. (return, assert etc)

When should you not use Lambda Functions?

In a production environment, You should never write complicated lambda functions, as it’ll be very difficult for coders who maintain your code to decrypt it.

They can tend to be difficult to understand if they have many arguments and can lead to slow debugging and collaboration especially with CodeNewbies

Lambdas are of the same class or type as their fellows defs; <class 'function'>

Resources: 📑

✔ Read More from Official Python Docs
✔ Real Python Article
✔ Free Code Camp Article

That's it!

If you enjoyed this article, consider subscribing to my channel for related content especially about Tech, Python & Programming.

📢Follow me on Twitter : ♥ ♥

Ronnie Atuhaire