Python Lambdas Explained: A Beginner’s Guide

TL;DR: Python lambdas are anonymous functions for single-line expressions and simple operations, often used with map, sorted, and reduce.

Sometimes, as you’re coding, you may need to create a function without naming it. These are called anonymous functions. In Python, we’ll be exploring a type of anonymous function known as a lambda. A lambda function can accept any number of arguments but returns only a single expression.

It is defined usong the lambda keyword, like this:

lamda args : expression

When run, it executes the given expression. Examine this example below

add_numbers = lambda num : num + 100

# Calling the function
print(add_numbers(5)) # Output: 105

We can see from the example above that when add_numbers was called with an arg , it executed the expression num + 100.

We can add more arguments:

# Accept more than one argument
multiply_nums = lambda a, b : a * b

print(multiply_nums(2, 3)) # Outpit: 6
# Accept many arguments
add_nums = lambda a, b, c, d, e : a + b + c + d + e

print(add_nums(2, 3, 6, 7, 9)) # Outpit: 27

Importance of Lambda functions

  • For single-line expressions

  • Suitable for use with some built-in functions like map, sorted and reduce.

  • For handling simple operation. If it becomes complex, it’s advisable to use def.

Simple Use Cases

Summarizing iterables

def reduce_num():
  numbers = [1, 2, 3, 4, 5, 6]
  result =  reduce(lambda x, y : x * y, numbers)

  return result

print(reduce_num()) # Output: 720

Squaring numbers:

def squared_nums():
  numbers = [1, 2, 3, 4, 5, 6]
  return list(map(lambda x : x * x, numbers))

print(squared_nums()) # Output: [1, 4, 9, 16, 25, 36]

Sorting list:

pairs = [(1, 'one'), (2, 'two'), (3, 'three')]
sorted_pairs = sorted(pairs, key=lambda pair: pair[1])
print(sorted_pairs)  # Output: [(1, 'one'), (3, 'three'), (2, 'two')]

By understanding and using lambda functions, you can write more concise and readable code for simple operations. Remember, if the logic becomes complex, it's better to use a regular function defined with def.