filter in python

In Python, filtering is often done using list comprehension with a conditional statement or a lambda function. Here are some examples:

  1. Using List Comprehension:
main.py
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)
# Output: [2, 4, 6, 8]
137 chars
5 lines
  1. Using Lambda Functions:
main.py
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]
140 chars
5 lines
  1. Using Boolean Expressions:
main.py
words = ['apple', 'banana', 'cherry', 'melon']
long_words = [word for word in words if len(word) > 5]
print(long_words)
# Output: ['banana', 'cherry']
151 chars
5 lines

These are just a few examples of how filtering can be implemented in Python. Different situations may require different filtering methods depending on the data type, size of the dataset, and other factors.

gistlibby LogSnag