Red Security
Tutorial Python 2.7: Filter Function with example - Printable Version

+- Red Security (https://redsecurity.info/cc)
+-- Forum: Programming (https://redsecurity.info/cc/forumdisplay.php?fid=5)
+--- Forum: Python (https://redsecurity.info/cc/forumdisplay.php?fid=9)
+--- Thread: Tutorial Python 2.7: Filter Function with example (/showthread.php?tid=7926)



Python 2.7: Filter Function with example - Covid-19 - 05-17-2022

[Image: BFMMlbcQvml9HSqXcvNp]

Filters In Python:
Filter function filters the iterables means it will return those items on which the given condition is true

Code:
#program to print each even number of list
mylist = [1,2,3,4,5,6,7,8,9]
mylist = list(filter(lambda x: x%2==0, mylist))
print(mylist)


It is not necessary to use lambda functions; you can also create your own functions and call them as  an argument in the filter function just like this.

Code:
mylist = [1,2,3,4,5,6,7,8,9]
def greaterThan(num):
    return num > 5
list_2 = list(filter(greaterThan,mylist))
print(list_2)


But using lambda functions make it easy to write code and readable.

Exclamation Note: We use filters with iterables like list, tuple etc..



RE: Python 2.7: Filter Function with example - Mr.Kurd - 05-20-2022

Nice, easy and short thanks man... Hopefully you give more example tho... I mean real life hacks.


RE: Python 2.7: Filter Function with example - Covid-19 - 05-20-2022

(05-20-2022, 01:01 PM)Mr.Kurd Wrote: Nice, easy and short thanks man... Hopefully you give more example tho... I mean real life hacks.

Thank you very much kurd. I'll try to give more real life example codes.