Programming Essentials Python - Map Reduce Libraries - Filtering Data using filter

Key Concept: Using filter on Iterable

We can use filter on top of an iterable to return a new iterable with all the elements satisfying the condition. It takes filter logic and the iterable as arguments. We can pass filter logic either as a regular function or a lambda function.

# Example of using filter
numbers = [1, 2, 3, 4, 5]
filtered_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(filtered_numbers))  # Output: [2, 4]

Key Concept: Type Casting filter object

filter returns a special iterable called filter. We have to type-cast it to a regular collection such as a list to preview the data or use a for loop to iterate and print the data.

# Type casting filter object
result_filter = filter(lambda x: x > 2, [1, 2, 3, 4, 5])
print(list(result_filter))  # Output: [3, 4, 5]

Hands-On Tasks

  1. Filter orders based on a specific customer ID.
  2. Filter orders based on customer ID and a specific month.
  3. Filter orders based on customer ID, month, and order statuses.

Conclusion

In this article, we explored how to use the filter function in Python to selectively filter elements from an iterable. By understanding the key concepts and hands-on tasks provided, readers can practice filtering data effectively. Further engagement with the community can enhance learning and problem-solving skills. Happy coding!

Watch the video tutorial here