In Python, a function is an object that receives input, modifies it, and returns some form of output. A lambda function is a one-line shorthand for a function, often used for simple tasks. Let's explore how lambda functions work and look at some practical examples.

Basic Syntax of Lambda Functions

A simple lambda function to add 2 to an input value can be expressed as follows:

# Lambda function to add 2 to the input value
add_two = lambda my_input: my_input + 2

# Testing the add_two lambda function with different inputs
print(add_two(3))
print(add_two(100))
print(add_two(-2))

would print:

>>> Output: 5
>>> Output: 102
>>> Output: 0

Let's break this syntax down:

  1. The function is assigned to a variable called 'add_two'.
  2. 'lambda'declares that this is a lambda function.
  3. 'my_input'is the parameter we pass into 'add_two'.
  4. The function returns 'my_input + 2'.

Lambda Function to Check Substrings

Here's an example of using a lambda function to check if a string contains any of a set of predefined substrings. This is useful for text analysis and keyword searches.

# Predefined set of substrings
keywords = ['python', 'lambda', 'function', 'code']

# Lambda function to check if any of the keywords is in the input string
contains_keyword = lambda text: any(keyword in text for keyword in keywords)

# Testing the contains_keyword lambda function with different inputs
print(contains_keyword('I love writing python code.'))
print(contains_keyword('Lambda functions are powerful.'))
print(contains_keyword('This is just a regular sentence.'))
print(contains_keyword('Functionality is key to good software.'))

would print:

>>> Output: True
>>> Output: True
>>> Output: False
>>> Output: True

Explanation:

  1. 'keywords' is a list of substrings we want to check for.
  2. 'contains_keyword' is a lambda function that returns 'True' if any keyword is found in the input 'Text', using a generator expression inside the 'any' function.

Conditional Logic in Lambda Functions

For the conditional logic example, let's create a lambda function that classifies numbers as 'Positive', 'Negative', or 'Zero'. This can be useful in numerical analysis or data validation tasks.

# Lambda function to classify numbers
classify_number = lambda num: 'Positive' if num > 0 else ('Negative' if num < 0 else 'Zero')

# Testing the classify_number lambda function with different inputs
print(classify_number(10))
print(classify_number(-5))
print(classify_number(0))
print(classify_number(3.14))
print(classify_number(-2.718))

would print:

>>> Output: 'Positive'
>>> Output: 'Negative'
>>> Output: 'Zero'
>>> Output: 'Positive'
>>> Output: 'Negative'

Explanation:

  1. 'classify_number' is a lambda function that takes a single parameter 'num'.
  2. It returns 'Positive' if 'num' is greater than 0.
  3. It returns 'Negative' if 'num' is less than 0.
  4. It returns 'Zero' if 'num' is exactly 0.

Limitations of Lambda Functions

Lambda functions are limited to a single expression. They are useful for short, simple functions but not suitable for more complex logic or multiple statements. They are often used for quick, throwaway operations.


Complex Lambda Function Example

While lambda functions are typically simple, you can create more complex expressions. Here’s an example that combines filtering and mapping over a list of dictionaries:

# List of dictionaries representing students and their grades
students = [
    {'name': 'Nima', 'grade': 85},
    {'name': 'Hani', 'grade': 92},
    {'name': 'Tina', 'grade': 87},
    {'name': 'Ashkan', 'grade': 78},
    {'name': 'Amir', 'grade': 91}
]

# Lambda function to filter and map student grades
process_students = lambda students: list(map(
    lambda student: {'name': student['name'], 'passed': student['grade'] >= 80},
    filter(lambda student: student['grade'] >= 80, students)
))

# Processing the students list
processed_students = process_students(students)

# Output the processed list of students
for student in processed_students:
    print(student)

The output is:

{'name': 'Nima', 'passed': True}
{'name': 'Hani', 'passed': True}
{'name': 'Tina', 'passed': True}
{'name': 'Amir', 'passed': True}

In this example:

  1. 'filter' is used to include only students with grades 80 and above.
  2. 'map' transforms the filtered students into a new list where each student dictionary includes a 'passed' key indicating if they passed.

 

Lambda functions in Python provide a concise way to write small functions. They are ideal for short operations, especially when used as arguments to higher-order functions like 'map', 'filter', and 'sorted'. However, for more complex operations, defining a standard function is often more appropriate.