Red Security

Full Version: Python 2.7: Filter Function with example
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
[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..
Nice, easy and short thanks man... Hopefully you give more example tho... I mean real life hacks.
(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.