Lambdas with sorted, map, and filter
π·οΈ Functions / Lambda Functions
π§ Context Introduction
Lambda functions are small, anonymous functions that can be defined in a single line. They are especially useful when you need a simple function for a short period, such as when working with sorted, map, and filter. Instead of writing a full function definition, you can use a lambda to keep your code concise and readable.
βοΈ What is a Lambda Function?
- A lambda function is defined using the keyword lambda, followed by parameters, a colon, and the expression to return.
- It can take any number of arguments but returns only one expression.
- Lambdas are often used as arguments to higher-order functions like sorted, map, and filter.
Basic syntax:
lambda arguments: expression
Example:
A lambda that adds two numbers: lambda x, y: x + y
π οΈ Using Lambdas with sorted()
The sorted() function returns a new sorted list from the elements of any iterable. You can customize the sorting behavior using the key parameter, which accepts a function. Lambdas are perfect here for defining simple sorting rules.
How it works: - sorted(iterable, key=lambda ...) applies the lambda to each element to determine the sort order. - The lambda returns a value that sorted() uses for comparison.
Example:
Sort a list of tuples by the second element:
sorted([(1, 3), (2, 1), (3, 2)], key=lambda x: x[1])
This returns [(2, 1), (3, 2), (1, 3)].
Another example:
Sort a list of strings by their length:
sorted(['apple', 'kiwi', 'banana'], key=lambda s: len(s))
This returns ['kiwi', 'apple', 'banana'].
πΊοΈ Using Lambdas with map()
The map() function applies a given function to every item in an iterable and returns a map object (which can be converted to a list). Lambdas make it easy to define the transformation on the fly.
How it works: - map(lambda ..., iterable) applies the lambda to each element. - The result is a new iterable with the transformed values.
Example:
Convert a list of temperatures in Celsius to Fahrenheit:
list(map(lambda c: (c * 9/5) + 32, [0, 10, 20, 30]))
This returns [32.0, 50.0, 68.0, 86.0].
Another example:
Square every number in a list:
list(map(lambda x: x ** 2, [1, 2, 3, 4]))
This returns [1, 4, 9, 16].
π΅οΈ Using Lambdas with filter()
The filter() function constructs an iterator from elements of an iterable for which a function returns True. Lambdas are ideal for writing the condition inline.
How it works: - filter(lambda ..., iterable) tests each element with the lambda. - Only elements that satisfy the condition (return True) are included in the result.
Example:
Filter out even numbers from a list:
list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 6]))
This returns [2, 4, 6].
Another example:
Keep only strings that start with the letter 'a':
list(filter(lambda s: s.startswith('a'), ['apple', 'banana', 'avocado', 'cherry']))
This returns ['apple', 'avocado'].
π Comparison Table: Lambda vs Regular Function
| Feature | Lambda Function | Regular Function (def) |
|---|---|---|
| Syntax | Single line, no name required | Multiple lines, requires a name |
| Use case | Simple, one-off operations | Complex logic or reusable code |
| Return | Implicitly returns the expression | Requires explicit return statement |
| Readability | Best for short, simple tasks | Better for longer or more complex logic |
| Reusability | Not reusable by name | Can be called by name anywhere |
π§ͺ Practical Tips for Engineers
- Use lambdas when the logic is simple and you don't need to reuse the function elsewhere.
- For complex conditions or multiple steps, always prefer a regular def function for clarity.
- Combine lambdas with sorted, map, and filter to write clean, expressive, and Pythonic code.
- Remember that map and filter return iterators; wrap them with list() if you need a list.
- Lambdas can also be used with other functions like min(), max(), and reduce() for similar benefits.
β Summary
- Lambda functions are anonymous, single-expression functions defined with the lambda keyword.
- sorted() with a lambda allows custom sorting logic without defining a separate function.
- map() with a lambda transforms each element in an iterable.
- filter() with a lambda selects elements that meet a condition.
- Lambdas keep your code short and focused, especially when used with these built-in functions.
By mastering lambdas with sorted, map, and filter, you can write more efficient and readable Python code for data processing tasks.
Lambda functions are small anonymous functions that can be used inline with Python's built-in functions like sorted, map, and filter to write concise code.
π’ Example 1: Basic lambda with sorted
Sorts a list of numbers in descending order using a lambda as the sorting key.
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers = sorted(numbers, key=lambda x: -x)
print(sorted_numbers)
π€ Output: [9, 6, 5, 4, 3, 2, 1, 1]
π΅ Example 2: Lambda with sorted and string length
Sorts a list of words by their length using a lambda function.
words = ["engineer", "code", "python", "ai", "data"]
sorted_by_length = sorted(words, key=lambda word: len(word))
print(sorted_by_length)
π€ Output: ['ai', 'code', 'data', 'python', 'engineer']
π‘ Example 3: Lambda with map to transform data
Converts a list of temperatures from Celsius to Fahrenheit using map with a lambda.
celsius = [0, 10, 20, 30, 40]
fahrenheit = list(map(lambda c: (c * 9/5) + 32, celsius))
print(fahrenheit)
π€ Output: [32.0, 50.0, 68.0, 86.0, 104.0]
π Example 4: Lambda with filter to select data
Filters a list of numbers to keep only even values using filter with a lambda.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
π€ Output: [2, 4, 6, 8, 10]
π΄ Example 5: Practical example β sorting engineers by experience
Sorts a list of engineer records by years of experience using a lambda as the sorting key.
engineers = [
{"name": "Alice", "experience": 5},
{"name": "Bob", "experience": 2},
{"name": "Charlie", "experience": 8},
{"name": "Diana", "experience": 3}
]
sorted_engineers = sorted(engineers, key=lambda eng: eng["experience"])
print(sorted_engineers)
π€ Output: [{'name': 'Bob', 'experience': 2}, {'name': 'Diana', 'experience': 3}, {'name': 'Alice', 'experience': 5}, {'name': 'Charlie', 'experience': 8}]
π Quick Comparison Table
| Function | Purpose | Lambda Input | Lambda Output |
|---|---|---|---|
sorted() |
Orders a collection | Each element | Value to sort by |
map() |
Transforms each element | Each element | Transformed value |
filter() |
Selects elements | Each element | Boolean (True/False) |
π§ Context Introduction
Lambda functions are small, anonymous functions that can be defined in a single line. They are especially useful when you need a simple function for a short period, such as when working with sorted, map, and filter. Instead of writing a full function definition, you can use a lambda to keep your code concise and readable.
βοΈ What is a Lambda Function?
- A lambda function is defined using the keyword lambda, followed by parameters, a colon, and the expression to return.
- It can take any number of arguments but returns only one expression.
- Lambdas are often used as arguments to higher-order functions like sorted, map, and filter.
Basic syntax:
lambda arguments: expression
Example:
A lambda that adds two numbers: lambda x, y: x + y
π οΈ Using Lambdas with sorted()
The sorted() function returns a new sorted list from the elements of any iterable. You can customize the sorting behavior using the key parameter, which accepts a function. Lambdas are perfect here for defining simple sorting rules.
How it works: - sorted(iterable, key=lambda ...) applies the lambda to each element to determine the sort order. - The lambda returns a value that sorted() uses for comparison.
Example:
Sort a list of tuples by the second element:
sorted([(1, 3), (2, 1), (3, 2)], key=lambda x: x[1])
This returns [(2, 1), (3, 2), (1, 3)].
Another example:
Sort a list of strings by their length:
sorted(['apple', 'kiwi', 'banana'], key=lambda s: len(s))
This returns ['kiwi', 'apple', 'banana'].
πΊοΈ Using Lambdas with map()
The map() function applies a given function to every item in an iterable and returns a map object (which can be converted to a list). Lambdas make it easy to define the transformation on the fly.
How it works: - map(lambda ..., iterable) applies the lambda to each element. - The result is a new iterable with the transformed values.
Example:
Convert a list of temperatures in Celsius to Fahrenheit:
list(map(lambda c: (c * 9/5) + 32, [0, 10, 20, 30]))
This returns [32.0, 50.0, 68.0, 86.0].
Another example:
Square every number in a list:
list(map(lambda x: x ** 2, [1, 2, 3, 4]))
This returns [1, 4, 9, 16].
π΅οΈ Using Lambdas with filter()
The filter() function constructs an iterator from elements of an iterable for which a function returns True. Lambdas are ideal for writing the condition inline.
How it works: - filter(lambda ..., iterable) tests each element with the lambda. - Only elements that satisfy the condition (return True) are included in the result.
Example:
Filter out even numbers from a list:
list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 6]))
This returns [2, 4, 6].
Another example:
Keep only strings that start with the letter 'a':
list(filter(lambda s: s.startswith('a'), ['apple', 'banana', 'avocado', 'cherry']))
This returns ['apple', 'avocado'].
π Comparison Table: Lambda vs Regular Function
| Feature | Lambda Function | Regular Function (def) |
|---|---|---|
| Syntax | Single line, no name required | Multiple lines, requires a name |
| Use case | Simple, one-off operations | Complex logic or reusable code |
| Return | Implicitly returns the expression | Requires explicit return statement |
| Readability | Best for short, simple tasks | Better for longer or more complex logic |
| Reusability | Not reusable by name | Can be called by name anywhere |
π§ͺ Practical Tips for Engineers
- Use lambdas when the logic is simple and you don't need to reuse the function elsewhere.
- For complex conditions or multiple steps, always prefer a regular def function for clarity.
- Combine lambdas with sorted, map, and filter to write clean, expressive, and Pythonic code.
- Remember that map and filter return iterators; wrap them with list() if you need a list.
- Lambdas can also be used with other functions like min(), max(), and reduce() for similar benefits.
β Summary
- Lambda functions are anonymous, single-expression functions defined with the lambda keyword.
- sorted() with a lambda allows custom sorting logic without defining a separate function.
- map() with a lambda transforms each element in an iterable.
- filter() with a lambda selects elements that meet a condition.
- Lambdas keep your code short and focused, especially when used with these built-in functions.
By mastering lambdas with sorted, map, and filter, you can write more efficient and readable Python code for data processing tasks.
Interactive Views
You are currently in π All-in-One mode. Use the tabs at the top to switch to π Theory Only or π» Code Only views.
Lambda functions are small anonymous functions that can be used inline with Python's built-in functions like sorted, map, and filter to write concise code.
π’ Example 1: Basic lambda with sorted
Sorts a list of numbers in descending order using a lambda as the sorting key.
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers = sorted(numbers, key=lambda x: -x)
print(sorted_numbers)
π€ Output: [9, 6, 5, 4, 3, 2, 1, 1]
π΅ Example 2: Lambda with sorted and string length
Sorts a list of words by their length using a lambda function.
words = ["engineer", "code", "python", "ai", "data"]
sorted_by_length = sorted(words, key=lambda word: len(word))
print(sorted_by_length)
π€ Output: ['ai', 'code', 'data', 'python', 'engineer']
π‘ Example 3: Lambda with map to transform data
Converts a list of temperatures from Celsius to Fahrenheit using map with a lambda.
celsius = [0, 10, 20, 30, 40]
fahrenheit = list(map(lambda c: (c * 9/5) + 32, celsius))
print(fahrenheit)
π€ Output: [32.0, 50.0, 68.0, 86.0, 104.0]
π Example 4: Lambda with filter to select data
Filters a list of numbers to keep only even values using filter with a lambda.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
π€ Output: [2, 4, 6, 8, 10]
π΄ Example 5: Practical example β sorting engineers by experience
Sorts a list of engineer records by years of experience using a lambda as the sorting key.
engineers = [
{"name": "Alice", "experience": 5},
{"name": "Bob", "experience": 2},
{"name": "Charlie", "experience": 8},
{"name": "Diana", "experience": 3}
]
sorted_engineers = sorted(engineers, key=lambda eng: eng["experience"])
print(sorted_engineers)
π€ Output: [{'name': 'Bob', 'experience': 2}, {'name': 'Diana', 'experience': 3}, {'name': 'Alice', 'experience': 5}, {'name': 'Charlie', 'experience': 8}]
π Quick Comparison Table
| Function | Purpose | Lambda Input | Lambda Output |
|---|---|---|---|
sorted() |
Orders a collection | Each element | Value to sort by |
map() |
Transforms each element | Each element | Transformed value |
filter() |
Selects elements | Each element | Boolean (True/False) |