How do you use lambda functions as arguments to higher-order functions like map, filter, and sorted
Using Lambda Functions with map, filter, and sorted in Python
Lambda functions are often used as arguments to higher-order functions like map, filter, and sorted to perform quick, one-time operations without defining a full-fledged function with "def". In this context, lambda functions provide a concise and expressive way to write functional code.
Here's how to use lambda functions with each higher-order function:
Using Lambda Functions with 'map':
A map function applies a given function to each element of an iterable (e.g., list, tuple) and returns an iterator containing the results. You can use a lambda function with 'map' to perform a specific operation on each element.
Syntax:
map(lambda arguments: expression, iterable)
Example:
# Find the cube of each list element.
nums = [1, 2, 3, 4, 5]
cube_numbers = map(lambda x: x ** 3, nums)
print(list(cube_numbers)) # Output: [1, 8, 27, 64, 125]
Using Lambda Functions with filter:
A filter function filters elements from an iterable based on a given condition (defined by a lambda function) and returns an iterator of elements that satisfy the condition.
Syntax:
filter(lambda arguments: condition, iterable)
Example:
# Find the odd numbers from a list of numbers
nums = [1, 2, 3, 4, 5]
odd_numbers = filter(lambda x: x % 2 != 0, nums)
print(list(odd_numbers)) # Output: [1, 3, 5]
Using Lambda Functions with sorted:
The sorted function sorts the elements of an iterable based on a specified key (defined by the lambda function) and returns a new sorted list.
Syntax:
sorted(iterable, key=lambda arguments: key_expression)
Example:
# Sort the elements of a list of strings
colors = ['red', 'white', 'green', 'orange']
sorted_colors = sorted(colors, key=lambda x: len(x))
print(sorted_colors) # Output:['red', 'white', 'green', 'orange']
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-interview/how-do-you-use-lambda-functions-as-arguments-to-higher-order-functions-like-map-filter-and-sorted.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics