Lambda functions, also known as anonymous functions, are a powerful feature in Python that allows you to define functions without giving them a name. These functions are created using the lambda keyword and are typically used for short, simple operations that are not reused elsewhere in the code.
The general syntax of a lambda function is:
lambda arguments: expression
This syntax defines a function that takes in some arguments and evaluates a single expression. The result of the expression is implicitly returned.
add = lambda x, y: x + y
print(add(3, 5)) # Output: 8
Lambda functions and regular (def-defined) functions can often be used interchangeably, but they have key differences:
def add(x, y):
return x + y
add = lambda x, y: x + y
The key differences include:
Lambda functions are most commonly used with higher-order functions that accept other functions as arguments. These include built-in functions like map(), filter(), reduce(), and sorted().
The map() function applies a function to all the items in an input list.
nums = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, nums))
print(squared) # Output: [1, 4, 9, 16]
The filter() function filters the items in an iterable for which the function returns True.
nums = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # Output: [2, 4]
The reduce() function (from the functools module) performs a rolling computation to sequential pairs of values in a list.
from functools import reduce
nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)
print(product) # Output: 24
You can use lambda to customize sorting behavior.
words = ['apple', 'banana', 'cherry', 'date']
sorted_words = sorted(words, key=lambda word: len(word))
print(sorted_words) # Output: ['date', 'apple', 'banana', 'cherry']
Lambda functions can include conditional logic using the ternary operator format.
max_func = lambda x, y: x if x > y else y
print(max_func(10, 20)) # Output: 20
Lambda functions can capture variables from their enclosing scopes, behaving like closures.
def make_incrementor(n):
return lambda x: x + n
inc_by_5 = make_incrementor(5)
print(inc_by_5(10)) # Output: 15
Despite their usefulness, lambda functions have limitations:
# This will raise a SyntaxError
lambda x: y = x + 1
You can use lambda functions within list comprehensions for custom processing.
funcs = [lambda x: x + n for n in range(3)]
results = [f(10) for f in funcs]
print(results) # Output: [12, 12, 12] due to late binding
To avoid the late binding issue, use default arguments:
funcs = [lambda x, n=n: x + n for n in range(3)]
results = [f(10) for f in funcs]
print(results) # Output: [10, 11, 12]
In GUI programming (e.g., Tkinter), lambda is used to define event handlers inline.
import tkinter as tk
root = tk.Tk()
button = tk.Button(root, text='Click me', command=lambda: print('Button clicked!'))
button.pack()
root.mainloop()
students = [
{'name': 'Alice', 'score': 88},
{'name': 'Bob', 'score': 95},
{'name': 'Charlie', 'score': 78}
]
sorted_students = sorted(students, key=lambda s: s['score'])
print(sorted_students)
multiply = lambda x, y, z: x * y * z
print(multiply(2, 3, 4)) # Output: 24
You can dynamically map operations using dictionaries of lambda functions.
operations = {
'add': lambda x, y: x + y,
'sub': lambda x, y: x - y,
'mul': lambda x, y: x * y,
'div': lambda x, y: x / y
}
print(operations['mul'](10, 5)) # Output: 50
Lambda functions are an integral part of functional programming paradigms in Python. They are heavily used alongside map, filter, and reduce, and often enable elegant solutions to complex problems in fewer lines.
str_nums = ['1', '2', '3']
int_nums = list(map(lambda x: int(x), str_nums))
print(int_nums) # Output: [1, 2, 3]
Lambda functions are very useful in data analysis and manipulation using the pandas library.
import pandas as pd
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie'],
'Score': [85, 92, 78]
})
df['Passed'] = df['Score'].apply(lambda x: x > 80)
print(df)
Lambda functions can be nested, although this reduces readability and is not common practice.
nested = lambda x: (lambda y: x + y)
add_to_10 = nested(10)
print(add_to_10(5)) # Output: 15
Use lambda functions when:
Use named functions when:
Lambda functions in Python offer a concise way to write simple functions without the need for a full function definition. They are especially useful in functional programming paradigms and when working with functions like map(), filter(), and sorted(). However, their limitationsβparticularly the inability to include multiple expressions and the lack of readability in complex logicβmean they should be used judiciously. When applied appropriately, lambda functions enhance code brevity and clarity.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved