Python filter() Function

The filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not.

https://www.w3schools.com/python/ref_func_filter.asp

In simple words, the filter() method filters the given iterable with the help of a function that tests each element in the iterable to be true or not.

https://www.programiz.com/python-programming/methods/built-in/filter

 

# list of alphabets
alphabets = ['a', 'b', 'd', 'e', 'i', 'j', 'o']

# function that filters vowels
def filterVowels(alphabet):
    vowels = ['a', 'e', 'i', 'o', 'u']

    if(alphabet in vowels):
        return True
    else:
        return False

filteredVowels = filter(filterVowels, alphabets)

print('The filtered vowels are:')
for vowel in filteredVowels:
    print(vowel)
    
# The filter() method returns an iterator that passed the function check for each element 
# in the iterable.
# In simple words, the filter() method filters the given iterable with the help of a 
# function that tests each element in the iterable to be true or not.

 

 

ages = [5, 12, 17, 18, 24, 32]
def myFunc(x):
  if x < 18:
    return False
  else:
    return True
adults = filter(myFunc, ages)
for x in adults:
  print(x)

 

 

def is_at_rich(dna): 
    length = len(dna) 
    a_count = dna.upper().count('A') 
    t_count = dna.upper().count('T') 
    at_content = (a_count + t_count) / length 
    if at_content > 0.65:
        return True
    else:
        return False

print(is_at_rich("ATTATCTACTA"))
print(is_at_rich("CGGCAGCGCT"))