Python Lamda Functions. No-name. One-line functions¶
Lamda function is a small function having just one expression and written in just one line. They don't need any function name. They are very handy when you need a small one-line code.
Lamda functions always start with lamda
What is Lambda?¶
A lambda function is a small function you write in one line, without even naming it. Here is how a normal function and its lamda counterpart would look like:
Where to Use Lambda¶
Lambda functions are handy for small, quick tasks where you don’t need a full function. Here are a few places where they are commonly used:
1. Sorting with Custom Rules¶
Let’s say you have a list of names and you want to sort them by length instead of alphabetically. Normally, you would write a function, but with a lambda, it’s easy:
Use lambda for sorting lists in a custom way.
2. Filtering Lists¶
If you have a list of numbers and you only want the even ones, lambda makes it easy:
Lambda functions are perfect for filtering lists.
3. Mapping Data¶
Let’s say you want to double every number in a list. Instead of writing a loop, you can use map()
with a lambda:
Use lambda to quickly transform data in lists.
4. Filtering with Lambda¶
If you need to filter out items from a list based on a condition, filter
with a lambda
function is a quick solution:
Lambda is great for filtering lists based on specific conditions.
5. Applying Lambda to a DataFrame¶
When working with data, you can use apply
with a lambda
function to perform operations on each element in a DataFrame column:
Apply lambda functions to DataFrame columns for quick data manipulation.
6. Combining Lambda with List Comprehensions¶
Sometimes, you might want to use a lambda function within a list comprehension for more complex operations:
Combine lambda functions with list comprehensions.
7. Lamda with IF-ELIF-ELSE¶
You can use a lambda function to quickly check if a number is odd or even:
You can use lamda with if IF-ELIF-ELSE logic
Let's recap¶
Don’t expect lambda functions to shrink your entire code. They’re only meant for small, one-line tasks where you don’t need to name the function.