Introduction
A lambda function is a small anonymous function that can have any number of arguments but only one expression. Lambda functions are useful when you need a short function for a simple task.
Lambda Syntax
The basic syntax is:
lambda arguments: expression
The expression is evaluated and automatically returned.
Simple Example
square = lambda x: x * x
print(square(5))
Output:
25
Multiple Arguments
multiply = lambda a, b: a * b
print(multiply(6, 7))
Using Lambda with sorted()
students = [
("Alice", 85),
("John", 92),
("Emma", 78)
]
students.sort(key=lambda student: student[1])
print(students)
Using Lambda with map()
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x * x, numbers))
print(squares)
Using Lambda with filter()
numbers = [1,2,3,4,5,6,7,8]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even)
Best Practices
- Use lambda functions only for simple operations.
- If the logic becomes complex, use a normal function.
- Use descriptive variable names.
- Keep lambda expressions readable.
Real-World Example
products = [
("Keyboard", 25),
("Mouse", 15),
("Monitor", 180)
]
products.sort(key=lambda product: product[1])
print(products)
Advantages
- Short and concise syntax.
- Perfect for one-time operations.
- Works well with
map(),filter()andsorted(). - Makes code cleaner for simple tasks.
Summary
Lambda functions provide a compact way to create small anonymous functions. They are especially useful when working with collections of data and are commonly used together with functions such as map(), filter(), and sorted().
Examples
The following examples help reinforce the concepts explained in this lesson.
<!DOCTYPE html>
<html>
<head>
<title>My First Page</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
💡 Pro Tip
Practice every concept immediately after reading it. Learning by doing is the fastest way to master HTML.
⚠ Common Mistake
Do not simply copy code examples. Type them yourself and experiment with small changes.
Best Practices
- Write clean and readable HTML.
- Indent your code consistently.
- Use semantic HTML elements.
- Validate your HTML regularly.
- Test your pages in multiple browsers.
Frequently Asked Questions
Why should I learn HTML first?
HTML is the foundation of every website. Once you understand HTML, learning CSS and JavaScript becomes much easier.
Is HTML difficult?
No. HTML is considered one of the easiest web technologies to learn, making it an excellent starting point for beginners.