Change language

filter () in python

|

syntax :

 filter (function, sequence)  Parameters:  function: function that tests if each element of a sequence true or not. sequence: sequence which needs to be filtered, it can be sets, lists, tuples, or containers of any iterators.  Returns:  returns an iterator that is already filtered. 

# function that filters vowels

def fun (variable):

letters = [ ’a’ , ’e’ , ’ i’ , ’ o’ , ’u’ ]

if (variable in letters):

return True

else :

return False

 

 
# sequence

sequence = [ ’g’ , ’ e’ , ’e’ , ’ j’ , ’k’ , ’ s’ , ’p’ , ’ r’ ]

 
# using the filter function

filtered = filter (fun, sequence)

 

print ( ’The filtered letters are: ’ )

for s in filtered:

print (s)

Exit :

 The filtered letters are: ee 

Application:
Usually used with

# the list contains even and odd numbers.

seq = [ 0 , 1 , 2 , 3 , 5 , 8 , 13 ]

 
# result contains odd list numbers

result = filter ( lambda x: x  % 2 , seq)

print ( list (result))

 
# result contains even list numbers

result = filter ( lambda x: x % 2 = = 0 , seq)

print ( list (result))

Exit:

 [1, 3, 5, 13] [0, 2, 8]  

Please refer to

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method