Related Articles

# Lambda and filter in Python Examples

• Difficulty Level : Basic
• Last Updated : 09 Jul, 2021

Prerequisite : Lambda in Python

Given a list of numbers, find all numbers divisible by 13.

```Input : my_list = [12, 65, 54, 39, 102,
339, 221, 50, 70]
Output : [65, 39, 221]
```

We can use Lambda function inside the filter() built-in function to find all the numbers divisible by 13 in the list. In Python, anonymous function means that a function is without a name.

The filter() function in Python takes in a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True.

 `# Python Program to find numbers divisible ``# by thirteen from a list using anonymous ``# function`` ` `# Take a list of numbers. ``my_list ``=` `[``12``, ``65``, ``54``, ``39``, ``102``, ``339``, ``221``, ``50``, ``70``, ]`` ` `# use anonymous function to filter and comparing ``# if divisible or not``result ``=` `list``(``filter``(``lambda` `x: (x ``%` `13` `=``=` `0``), my_list)) `` ` `# printing the result``print``(result) `

Output:

```[65, 39, 221]
```

Given a list of strings, find all palindromes.

 `# Python Program to find palindromes in ``# a list of strings.`` ` `my_list ``=` `[``"geeks"``, ``"geeg"``, ``"keek"``, ``"practice"``, ``"aa"``]`` ` `# use anonymous function to filter palindromes.``# Please refer below article for details of reversed``# https://www.geeksforgeeks.org/reverse-string-python-5-different-ways/``result ``=` `list``(``filter``(``lambda` `x: (x ``=``=` `"".join(``reversed``(x))), my_list)) `` ` `# printing the result``print``(result) `

Output :

```['geeg', 'keek', 'aa']
```

Given a list of strings and a string str, print all anagrams of str

 `# Python Program to find all anagrams of str in ``# a list of strings.``from` `collections ``import` `Counter`` ` `my_list ``=` `[``"geeks"``, ``"geeg"``, ``"keegs"``, ``"practice"``, ``"aa"``]``str` `=` `"eegsk"`` ` `# use anonymous function to filter anagrams of x.``# Please refer below article for details of reversed``# https://www.geeksforgeeks.org/anagram-checking-python-collections-counter/``result ``=` `list``(``filter``(``lambda` `x: (Counter(``str``) ``=``=` `Counter(x)), my_list)) `` ` `# printing the result``print``(result) `

Output :

```['geeks', 'keegs']
```

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up