Python — Understanding Advanced Concepts with Ease: Day 5 (Lambda, Map & Filter)

Dipan Saha
4 min readJan 27, 2024

--

Photo by David Clode on Unsplash

Welcome back to Day 5 of our Python — Understanding Advanced Concepts with Ease series! Let’s learn something new today.

Lambda

In python, a lambda function is a small anonymous function that can have any number of arguments but only one expression. They are also known as inline functions or anonymous functions because they don’t require a formal name like regular functions.

Examples

Here’s a simple explanation with an example:

Imagine you need a quick function to double a number. You could define a regular function like this:

def double(x):
return x * 2

But what if you only need to use this function once, and you don’t want to clutter your code with a full-fledged function definition? That’s where lambda functions come in handy!

You can create a lambda function to double a number like this:

double = lambda x: x * 2

Now, double is a lambda function that takes one argument x and returns x * 2. It's like a shortcut for creating simple functions on the fly.

You can use lambda functions in many places where you would use regular functions. For example, you can pass them as arguments to other functions like map(), filter(), or sorted().

Sorted

In Python, the sorted() function is a built-in function that sorts an iterable (such as a list, tuple, or string) and returns a new sorted list. It doesn't modify the original iterable but instead creates a new sorted version of it.

Here’s a simple explanation with examples:

  • Sorting a List of Numbers:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 1, 2, 3, 4, 5, 5, 6, 9]
  • Sorting a List of Strings:
names = ["Alice", "Bob", "Charlie", "David"]
sorted_names = sorted(names)
print(sorted_names) # Output: ['Alice', 'Bob', 'Charlie', 'David']
  • Sorting a String:
text = "python"
sorted_text = sorted(text)
print(sorted_text) # Output: ['h', 'n', 'o', 'p', 't', 'y']
  • Sorting a List of Tuples by a Specific Element:
people = [("Alice", 30), ("Bob", 25), ("Charlie", 35), ("David", 28)]
sorted_people = sorted(people, key=lambda x: x[1]) # Sort by age
print(sorted_people)
# Output: [('Bob', 25), ('David', 28), ('Alice', 30), ('Charlie', 35)]

A few important points to note!

  • The sorted() function returns a new sorted list, leaving the original iterable unchanged.
  • By default, the sorting is done in ascending order, but you can specify the reverse=True argument to sort in descending order.
  • For sorting more complex data structures like lists of tuples, you can use the key parameter to specify a function that extracts a value to use for sorting.

Map

In Python, the map() function helps you transform every item in a list or another iterable using a given rule or function. It takes two arguments: the function you want to apply and the list or iterable you want to transform. Then, it gives you back a new iterable with all the items transformed according to your rule.

Essentially, it allows you to perform the same operation on every element of a collection without needing to write a loop explicitly.

Syntax

The syntax of the map() function is as follows:

map(function, iterable)
  • function: The function to apply to each element of the iterable.
  • iterable: The iterable (e.g., list, tuple, etc.) whose elements will be processed by the function.

Examples

Here is a simple example demonstrating the map function:

# Define a list of numbers
numbers = [1, 2, 3, 4, 5]

# Use map() with a lambda function to square each number
squared_numbers = map(lambda x: x**2, numbers)

# Convert the map object to a list to see the result
squared_numbers_list = list(squared_numbers)

print(squared_numbers_list) # Output: [1, 4, 9, 16, 25]

A more advance example will look like this:

# Define lists of student names and scores
student_names = ["Alice", "Bob", "Charlie", "David"]
scores = [85, 90, 78, 95]

# Use map() with a lambda function to calculate average scores
average_scores = map(
lambda name, score: (name, score / len(scores)), student_names, scores
)

# Convert the map object to a dictionary for easier visualization
average_scores_dict = dict(average_scores)

print(average_scores_dict)

Filter

In Python, the filter() function is a built-in function used to filter elements from an iterable (such as a list) based on a given condition. It returns an iterator containing only the elements for which the condition evaluates to True.

Here’s a simple explanation with examples:

  • Filtering Even Numbers from a List:
# Define a list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Use filter() to filter even numbers
even_numbers = filter(lambda x: x % 2 == 0, numbers)

# Convert the filter object to a list
even_numbers_list = list(even_numbers)

print(even_numbers_list) # Output: [2, 4, 6, 8, 10]
  • Filtering Names Starting with ‘A’ from a List:
# Define a list of names
names = ["Alice", "Bob", "Charlie", "David", "Anna", "Amy"]

# Use filter() to filter names starting with 'A'
a_names = filter(lambda name: name.startswith('A'), names)

# Convert the filter object to a list
a_names_list = list(a_names)

print(a_names_list) # Output: ['Alice', 'Anna', 'Amy']
  • Filtering Positive Numbers from a List:
# Define a list of numbers
numbers = [-3, 5, -7, 10, -2, 8, 0]

# Use filter() to filter positive numbers
positive_numbers = filter(lambda x: x > 0, numbers)

# Convert the filter object to a list
positive_numbers_list = list(positive_numbers)

print(positive_numbers_list) # Output: [5, 10, 8]

Conclusion

Congratulations! Hope you learnt something new today. See you on Day 6.

Happy coding!

--

--

Dipan Saha

Cloud Architect (Certified GCP Professional Architect & Snowflake Core Pro)