1. Simple Arithmetic Operations:
add = lambda x, y: x + y
subtract = lambda x, y: x - y
multiply = lambda x, y: x * y
divide = lambda x, y: x / y
print(add(3, 5)) # Output: 8
print(subtract(8, 3)) # Output: 5
print(multiply(4, 6)) # Output: 24
print(divide(10, 2)) # Output: 5.0
#clcoding.com
8
5
24
5.0
2. Sorting a List of Tuples :
pairs = [(1, 5), (2, 3), (4, 1), (3, 8)]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs) # Output: [(4, 1), (2, 3), (1, 5), (3, 8)]
#clcoding.com
[(4, 1), (2, 3), (1, 5), (3, 8)]
3. Filtering a List:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6, 8]
#clcoding.com
[2, 4, 6, 8]
4. Mapping a Function to a List:
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
#clcoding.com
[1, 4, 9, 16, 25]
5. Using Lambda with map and filter:
# Doubling each element in a list using map
numbers = [1, 2, 3, 4, 5]
doubled_numbers = list(map(lambda x: x * 2, numbers))
print(doubled_numbers) # Output: [2, 4, 6, 8, 10]
# Filtering odd numbers using filter
odd_numbers = list(filter(lambda x: x % 2 != 0, numbers))
print(odd_numbers) # Output: [1, 3, 5]
#clcoding.com
[2, 4, 6, 8, 10]
[1, 3, 5]
6. Using Lambda in Key Functions:
# Sorting a list of strings based on the length of each string
words = ['apple', 'banana', 'kiwi', 'orange']
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words) # Output: ['kiwi', 'apple', 'banana', 'orange']
#clcoding.com
['kiwi', 'apple', 'banana', 'orange']
7. Creating Functions on the Fly:
# Creating a simple calculator with lambda functions
calculator = {
'add': lambda x, y: x + y,
'subtract': lambda x, y: x - y,
'multiply': lambda x, y: x * y,
'divide': lambda x, y: x / y,
}
result = calculator['multiply'](4, 5)
print(result) # Output: 20
#clcoding.com
20
8. Using Lambda in List Comprehensions:
# Squaring each element in a list using list comprehension
numbers = [1, 2, 3, 4, 5]
squared_numbers = [(lambda x: x**2)(x) for x in numbers]
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
#clcoding.com
[1, 4, 9, 16, 25]
9. Lambda Functions in Higher-Order Functions:
# A higher-order function that takes a function as an argument
def operate_on_numbers(x, y, operation):
return operation(x, y)
# Using a lambda function as an argument
result = operate_on_numbers(10, 5, lambda x, y: x / y)
print(result) # Output: 2.0
#clcoding.com
2.0
0 Comments:
Post a Comment