How to use Python Lambda, Map and Filter Functions

How to use Python Lambda, Map and Filter Functions

Python is a versatile programming language known for its readability and ease of use. Among its many features, Python supports functional programming concepts, which allow you to write concise and expressive code. In this article, we’ll explore three important functions in Python’s functional programming arsenal: lambda, map, and filter. These functions can help you write more efficient and elegant code for common data manipulation tasks.

Using Lambda Functions

A lambda function in Python is a small, anonymous function defined using the lambda keyword. Lambda functions can have any number of arguments but can only have one expression. They are particularly useful when you need a simple function for a short period of time.

# Example of a lambda function
add = lambda x, y: x + y
print(add(3, 5)) # Output: 8

In the above example, we define a lambda function add that takes two arguments x and y and returns their sum.

Real-Life Example of Lamba Function

Creating a Simple Calculator

# Lambda functions for basic 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 if y != 0 else "Division by zero!"

# Using the lambda functions
print(add(5, 3)) # Output: 8
print(subtract(7, 2)) # Output: 5
print(multiply(4, 6)) # Output: 24
print(divide(8, 2)) # Output: 4.0
print(divide(5, 0)) # Output: Division by zero!

In this example, we define lambda functions for basic arithmetic operations and then use them to perform calculations.

Filtering a List of Strings

names = ['Alice', 'Bob', 'Charlie', 'David', 'Eve']
# Filter names that start with 'A'
filtered_names = list(filter(lambda x: x.startswith('A'), names))
print(filtered_names) # Output: ['Alice']

Here, we use a lambda function with the filter function to keep only the names that start with the letter ‘A’.

Sorting a List of Tuples

points = [(1, 2), (3, 1), (5, 3), (4, 6)]
# Sort by the sum of tuple elements
sorted_points = sorted(points, key=lambda x: x[0] + x[1])
print(sorted_points) # Output: [(1, 2), (3, 1), (5, 3), (4, 6)]

In this example, we use a lambda function as the key argument in the sorted function to sort a list of tuples based on the sum of their elements.

Using Map Function

The map function in Python applies a given function to each item of an iterable (such as a list) and returns a new iterable with the results. It takes two arguments: the function to apply and the iterable to process.

# Example of using map function
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]

In this example, we use a lambda function with map to square each number in the numbers list.

Real-Time Example of Map Function

Converting Temperatures

# Function to convert Celsius to Fahrenheit
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32

# List of temperatures in Celsius
temperatures_celsius = [0, 10, 20, 30, 40]

# Using map to convert temperatures to Fahrenheit
temperatures_fahrenheit = list(map(celsius_to_fahrenheit, temperatures_celsius))
print(temperatures_fahrenheit)
# Output: [32.0, 50.0, 68.0, 86.0, 104.0]

In this example, the map function applies the celsius_to_fahrenheit function to each temperature in the temperatures_celsius list, converting them to Fahrenheit.

Applying Discounts

# Function to apply a discount to a price
def apply_discount(price):
return price * 0.9 # 10% discount

# List of prices
prices = [100, 200, 300, 400, 500]

# Using map to apply discount to prices
discounted_prices = list(map(apply_discount, prices))
print(discounted_prices)
# Output: [90.0, 180.0, 270.0, 360.0, 450.0]

Here, the map function applies the apply_discount function to each price in the prices list, calculating the discounted price.

Generating Power Values

# Function to calculate the square of a number
def square(x):
return x ** 2

# List of numbers
numbers = [1, 2, 3, 4, 5]

# Using map to calculate the squares of numbers
squares = list(map(square, numbers))
print(squares)
# Output: [1, 4, 9, 16, 25]

In this example, the map function applies the square function to each number in the numbers list, calculating the square of each number.

Using Filter Function

The filter function in Python constructs an iterator from elements of an iterable for which a function returns true. It takes two arguments: the function to apply and the iterable to process.

# Example of using filter function
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]

Here, we use a lambda function with filter to keep only the even numbers from the numbers list.

Story: The Tale of Python and the Functions

Once upon a time, in the land of programming, there were two kingdoms: Python and Java. Python was known for its simplicity and readability, while Java was known for its performance and versatility. The two kingdoms coexisted peacefully, each with its own strengths and weaknesses.

One day, a young programmer named Alice arrived in the kingdom of Python, eager to learn the ways of programming. She was fascinated by the lambda, map, and filter functions, which allowed her to write powerful and expressive code with ease. With these functions, she could manipulate data in ways she never thought possible, making her programs more efficient and elegant.

As Alice delved deeper into the world of Python, she discovered the lambda function, a small but mighty tool that allowed her to create anonymous functions on the fly. With lambda, she could write concise and powerful functions without the need for a formal definition.

Next, Alice learned about the map function, which allowed her to apply a function to each item in a list and return a new list with the results. This was incredibly useful for transforming data in her programs, making them more dynamic and flexible.

Finally, Alice learned about the filter function, which allowed her to selectively extract elements from a list based on a condition. This helped her clean and filter her data with ease, making her programs more robust and reliable.

Conclusion

In conclusion, Python’s lambda, map, and filter functions are powerful tools that can help you write more efficient and elegant code. By mastering these functions, you can manipulate data in ways that were once thought impossible, making your programs more dynamic and flexible. Whether you’re a beginner or an experienced programmer, learning these functions will enhance your Python skills and take your programming to the next level.

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>