Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Lists
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- Set Comprehensions
- String Formatting
- Indexing and Slicing
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Object-Oriented Programming (OOP)
- Object-Oriented Programming
- Classes and Objects
- the `__init__()` Constructor
- Instance Variables and Methods
- Class Variables and `@classmethod`
- Encapsulation and Data Hiding
- Inheritance and Subclasses
- Method Overriding and super()
- Polymorphism
- Magic Methods and Operator Overloading
- Static Methods
- Abstract Classes and Interfaces
Python Programs
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
Lambda Functions in Python: Guide to Anonymous Functions
Python is known for its readability, simplicity, and powerful features. One such feature, often underestimated by beginners, is the lambda function—also known as an anonymous function. Despite their compact appearance, lambda functions pack a punch when it comes to writing elegant, one-liner functions.
This guide will walk you through everything you need to know about lambda functions in Python. Whether you’re building a filter system, sorting data, or working with functional programming, lambdas can be your secret weapon.
📌 What Are Lambda Functions in Python?
Lambda functions are small, anonymous functions defined using the lambda
keyword. Unlike regular functions declared using def
, lambdas can be created in a single line of code and are typically used when a function is only needed temporarily or for a short task.
👉 Syntax:
lambda arguments: expression
This function returns the value of the expression when called with the provided arguments.
🧠 Why Are Lambda Functions Important?
Here’s why you should learn about and use lambda functions:
- ✅ Concise Code: Ideal for small, one-time-use functions.
- ✅ Improved Readability: When used correctly, they make your code cleaner.
- ✅ Functional Programming: Work well with functions like
map()
,filter()
, andreduce()
. - ✅ Anonymous: You don’t need to give them a name unless necessary.
✅ Prerequisites
Before you dive in, you should be comfortable with:
- Basic Python functions (
def
) - Understanding arguments and return values
- Using higher-order functions (optional, but helpful)
🔍 Defining Lambda Functions: A Closer Look
Let’s start with a simple example.
✅ Regular Function:
def add(x, y):
return x + y
print(add(5, 3)) # Output: 8
✅ Lambda Equivalent:
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8
As you can see, both do the same thing, but the lambda version is more concise.
🔄 Lambda with map()
, filter()
, and reduce()
📌 map()
– Apply a function to all items in a list
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16]
📌 filter()
– Filter items using a condition
nums = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even) # Output: [2, 4, 6]
📌 reduce()
– Reduce a list to a single value
from functools import reduce
product = reduce(lambda x, y: x * y, [1, 2, 3, 4])
print(product) # Output: 24
🔃 Sorting with Lambda Functions
Lambda functions are great when sorting complex data structures like lists of dictionaries or tuples.
✅ Sort by second element in a list of tuples:
pairs = [(1, 2), (3, 1), (5, 0)]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs) # Output: [(5, 0), (3, 1), (1, 2)]
✅ Sort list of dictionaries by value:
students = [
{"name": "Alice", "score": 88},
{"name": "Bob", "score": 95},
{"name": "Charlie", "score": 78}
]
top_scorers = sorted(students, key=lambda x: x['score'], reverse=True)
print(top_scorers)
🔬 Real-World Examples
1. Event Handling in GUI Applications
button.click(lambda event: print("Button clicked!"))
2. Sorting API Results
data = [{"id": 1, "views": 100}, {"id": 2, "views": 300}]
data.sort(key=lambda x: x["views"])
3. Custom Key Extraction
words = ["python", "lambda", "function"]
words.sort(key=lambda x: len(x))
4. Conditional List Operations
names = ["John", "Ann", "Mike"]
filtered = list(filter(lambda x: len(x) > 3, names))
5. Inline Mathematical Operations
triple = lambda x: x * 3
print(triple(4)) # Output: 12
⚠️ Common Mistakes to Avoid
-
Trying to write multiple expressions: Lambda functions can only have one expression (no loops, multiple lines, or assignments).
❌ Wrong:
lambda x: x = x + 1 # SyntaxError
-
Overusing lambdas: Don’t use lambdas where a named function with
def
improves readability. -
Using lambdas in deeply nested code: While lambdas are concise, avoid cluttering your code with too many anonymous functions in one place.
🧾 Best Practices
- ✅ Use lambdas when a short, throwaway function is needed.
- ✅ Keep expressions simple and readable.
- ✅ Prefer
def
for complex logic or reuse. - ✅ Pair lambdas with built-in functions like
map
,filter
,sorted
, andreduce
.
Lambda functions are one of Python’s elegant features that give your code flexibility and brevity. They are perfect when you need small, unnamed functions for one-off tasks, especially in functional programming contexts. By understanding when and how to use them effectively, you can write cleaner, faster, and more Pythonic code.
So the next time you’re about to define a quick function, ask yourself—could a lambda do this better?