Python Programming Tips – Lambda Functions and Filter

Today, we will look at another exciting combination technique in Python.

Let’s start with a pure music piece~

filter() is a built-in higher-order function in Python used to filter iterable objects (such as lists, tuples, etc.). By combining it with a lambda function, we can succinctly define filtering conditions. For example, filtering even numbers:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]# Using lambda + filter to select even numbers
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6, 8, 10]

Another example is filtering a list of dictionaries (such as people aged 18 and above):

people = [    {"name": "Alice", "age": 17},    {"name": "Bob", "age": 22},    {"name": "Charlie", "age": 15},    {"name": "David", "age": 30}]# Filtering people aged ≥ 18
adults = list(filter(lambda person: person["age"] >= 18, people))
print(adults)# Output: [{'name': 'Bob', 'age': 22}, {'name': 'David', 'age': 30}]

All of this can be done in just one line of code, concise and practical!

As the music ends, today’s learning also comes to a close~

Recommended Reading

  • Basic Python Algorithms – Get the Largest k Elements in One Line of Code

  • Basic Python Algorithms – Get the Largest k Elements
  • Prime Number Determination (Square Root Complexity)
  • Basic Python Algorithms – Prime Number Determination
  • Python Programming Tips – Lambda Functions and Map

  • Python Programming Tips – Lambda Functions and Map

  • Basic Python Algorithms – Implementing List Left Rotation in One Line of Code

  • Basic Python Algorithms – Implementing List Left Rotation in One Line of Code

  • Basic Python Algorithms – Narcissistic Number Determination

  • Basic Python Algorithms – Narcissistic Number Determination

Here we have programming, algorithms, large models, and music (popular/indie). Click to follow, let’s learn together and improve every day~

Leave a Comment