Lambdas

Python SELF EN
Level 13 , Lesson 2
Available

2.1 Defining Lambda Functions

Lambda functions, also known as anonymous functions, are compact, single-line functions without a name, which can be created using the lambda keyword.

Unlike regular functions defined using def, lambda functions are created on the fly and are typically used for simple operations that are executed in a single line.

The syntax of a lambda function consists of the lambda keyword, followed by arguments, a colon, and an expression:

 
lambda arguments: expression
    

Lambda functions can take any number of arguments but can contain only one expression. The value of this expression is automatically returned.

Examples:

Lambda Function Regular Function

square = lambda x: x ** 2
print(square(5))  # Output: 25
                    

def square(x):
    return x ** 2
print(square(5))  # Output: 25
                

sum = lambda a, b: a + b
            

def sum(a, b):
    return a + b
                

up = lambda s: s.upper()
            

def up(s):
    return s.upper()
                    

2.2 Using Lambda Functions

Lambda functions are often used in conjunction with other functions, like map(), filter(), and sorted(), as well as being passed as arguments to other functions.

Usage with map()

The map() function applies a given function to each item of an iterable and returns an iterator with results. Lambda functions are great to use with map() since they allow you to define a function to transform the elements concisely.


numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers)  # Output: [1, 4, 9, 16, 25]
        

Usage with filter()

The filter() function returns an iterator with elements of the iterable for which the given function returns True. Lambda functions allow you to quickly define a filtering condition.


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # Output: [2, 4, 6, 8, 10]

Usage with sorted()

The sorted() function sorts the elements of an iterable. Lambda functions can be used to define a custom sorting criteria using the key argument.


words = ["banana", "apple", "cherry", "date"]
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words)  # Output: ['date', 'apple', 'banana', 'cherry']
        

Lambda Functions in Expressions

Lambda functions can be used inside other expressions such as list comprehensions and dictionary comprehensions.


pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs)  # Output: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
        

2.3 Limitations of Lambda Functions

Lambda functions have some limitations compared to regular functions:

Limited to Expressions:

Lambda functions can only contain a single expression and can't include complex statements such as loops or flow-control statements (like if, else, etc.).

No Documentation:

Lambda functions can't contain a docstring, which makes it hard to document their functionality.

Limited Debugging Capabilities:

Due to the lack of a name and documentation, lambda functions are harder to debug than regular functions.

Example of Lambda Function Limitation

Attempting to use multiple expressions in a lambda function will result in a syntax error:


# This code will cause an error
invalid_lambda = lambda x: x ** 2; print(x)
        
    
2
Task
Python SELF EN, level 13, lesson 2
Locked
Lambda squared.
Lambda squared.
2
Task
Python SELF EN, level 13, lesson 2
Locked
Sorting.
Sorting.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION