Advanced Python Lambda: Using map, filter, and sorted Together
Advanced Python Lambda: Using map, filter, and sorted Together ๐ฅ
lambda expressions in Python allow you to create small anonymous functions on the fly.
When combined with functions like map(), filter(), and sorted(),
they enable a clean and powerful functional programming style.
✅ Using lambda with map()
map() applies a function to each element in an iterable.
# lambda with map: transforming a list
nums = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, nums))
print(squared) # [1, 4, 9, 16]
✅ Using lambda with filter()
filter() selects only elements that satisfy a given condition.
# lambda with filter: selecting elements
nums = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even) # [2, 4, 6]
✅ Using lambda with sorted()
Pass a key function to sorted() to customize the sort order.
# lambda with sorted: custom sorting
words = ["banana", "apple", "cherry"]
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words) # ['apple', 'banana', 'cherry']
lambda expressions shine when you need quick, throwaway functions.
For more complex logic, prefer using named functions to maintain readability.
Concise and readable code is powerful code. Mastering lambda gives your Python skills a professional edge. ๐
Icons by Flaticon
Comments
Post a Comment