Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

Filter() in Python

Last updated by Vartika Rai on Apr 01, 2024 at 01:48 PM | Reading time: 7 minutes

The fast well prepared banner

Attend our Free Webinar on How to Nail Your Next Technical Interview

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

Filter() in Python
Hosted By
Ryan Valles
Founder, Interview Kickstart
strategy
Our tried & tested strategy for cracking interviews
prepare list
How FAANG hiring process works
hiring process
The 4 areas you must prepare for
hiring managers
How you can accelerate your learnings

To filter means to separate something. In programming, it means separating some data from a large set of data. This is exactly what the filter() method in python does. It accepts a sequence of values and a condition, and it filters out values that match that condition. If you’re a software engineer preparing for a technical interview, you must be aware of use cases of such functions, as they’ll help you break down complex tasks into smaller chunks and hence write simpler code. 

This article will cover the filter function in detail:

  • What is filter() in Python?
  • Filtering a List Using Python’s filter() Method
  • Problems on Python’s filter() Method
  • FAANG interview questions on Python’s filter() Method
  • FAQs on Python’s filter() Method

What Is filter() in Python?

filter() in Python accepts a sequence (an iterable object) and returns a subsequence (also an iterable object) based on a given condition.

Suppose you are given a list of positive integers, and your task is to find only those numbers that are even and also divisible by 3. The basic idea here is to iterate through all values and check if the value is even and also divisible by 3. If both conditions are met, store these values in another list and finally print that list. But in Python, you can solve this problem in much fewer lines of code with the help of filter().

filter() accepts two arguments: first is a function and the other something we can iterate through (also known as iterable objects. For example, list, set, tuple, etc.)

Syntax of filter():

filter(function, iterable)

Parameters of filter():

  • function: If this parameter is passed, then each element of the sequence will be tested by this function. If not passed, then filter() will filter out all elements from the sequence that is False, 0, None, or an empty string.
  • Iterable: Any data structure that supports iteration, such as list, tuple, string, etc.

Return value of filter():

filter() returns a filter object, which is of class <class 'filter'>

Let’s see the solution of the above problem without the help of filter() in Python:

def check(value):
return (value % 2 == 0) and (value % 3 == 0)

user_list = [1, 2, 3, 4, 6, 9, 4, 1, 5, 4, 12]
filtered_list = []

for value in user_list:
if(check(value)):
filtered_list.append(value)

print(filtered_list)

'''
Output
[6, 12]
'''

Let’s implement the same solution with the help of filter() in Python:

def check(value):
return (value % 2 == 0) and (value % 3 == 0)

user_list = [1, 2, 3, 4, 6, 9, 4, 1, 5, 4, 12]

filtered_list = filter(check, user_list)
print(list(filtered_list))

'''
Output
[6, 12]
'''

You don’t need to always define the function argument in filter(). If the function argument is None, the identity function is assumed — filter() removes those elements that are False, None, 0, or an empty string from the iterable.

In the code below, we filter out all the values that aren’t None, an empty string, 0, or False without the help of filter().

def check(value):
if value:
return True
return False

user_list = [1, 2, 3, 4, "", 0, None]
filtered_list = []
for x in user_list:
if check(x):
filtered_list.append(x)
print(list(filtered_list))

'''
Output
[1, 2, 3, 4]
'''

In the following code, we use filter(). We call it by passing None and user_list as parameters — None is the function argument, and user_list contains different types of values, including None and an empty string. The return value of filter() will be all the values like False, 0, None, or an empty string.

user_list = [0, 1, 2, 4, None, 1, 5, "", 4, 12]

filtered_list = filter(None, user_list)
print(list(filtered_list))

'''
Output
[1, 2, 4, 1, 5, 4, 12]
'''

Filtering a List Using Python’s filter() Method

We know now that filter() accepts an iterable as an argument, where it can perform some checks, and based on the condition, it returns an iterable object.

Let’s solve a problem with the help of filter() in Python on a list.

Problem: Given a list of strings, return a list containing all strings with three consecutive characters “a” in it.

def check(s):
return "aaa" in s

user_list = ["asfdc", "aabbaaac", "cdfdccc", "baaab", "baab"]

filtered_list = filter(check, user_list)
print(list(filtered_list))

'''
Output
['aabbaaac', 'baaab']
'''

Problems on filter()

Problem 1: Filter all numbers in a list of numbers whose bitwise xor with the given value x is equal to 4 with the help of filter() in Python.

'''input
5
1 2 3 4 5 6 7
'''
value = int(input())
user_list = list(map(int, input().strip().split()))

filtered_list = filter(lambda x: (x ^ 5 == 4), user_list)
print(list(filtered_list))

'''
Output
[1]

'''

Problem 2: How do you use filter() for filtering the list of dictionaries?

Answer: We iterate through all dictionary objects in the list and check for the condition in function; if the dictionary object passes the condition, we return that object; otherwise, we remove the object.

user_list = [{
"type": "integer",
"value": "10",
}, {
"type": "decimal",
"value": "10.01",
}, {
"type": "integer",
"value": "4"
}, {
"type": "string",
"value": "str",
}]

filtered_list = filter(lambda x: (x["type"] == "integer"), user_list)
print(list(filtered_list))

'''
Output
[{'type': 'integer', 'value': '10'}, {'type': 'integer', 'value': '4'}]
'''

FAANG Interview Questions on Python’s filter() method

  1. Count the number of pairs in a given range of positive integers whose bitwise AND operation is equal to bitwise OR operation.
  2. Count total numbers of integers in a given range whose sum of digits is equal to the given value where value <= 100.
  3. Given a dictionary of vocabulary, find all the words in the dictionary whose meaning contains a given string as a substring.
Learn more here:
-
Interview Questions
-
Problems

FAQs on filter()

Question 1: Can filter() be applied on string data type

Answer: Yes, filter() can be applied on string data type because the string in Python is also iterable. Here is an example on filter() on string().

Problem: Find a string of consonants from the given string

def check(s):
if s in ['a', 'e', 'i', 'o', 'u']:
return False
return True

user_string = "alsjfdlaasdfknmnsfwirqpadsf"
filtered_list = filter(check, user_string)
print("".join(filtered_list))

'''
Output
lsjfdlsdfknmnsfwrqpdsf
'''

Question 2: What does filter() return in Python?

Answer: filter() in Python returns a filter object which is iterable, and all the filtered value can be printed by iterating through the filtered object.

For example, if we simply print filtered_list in the above problem, the output will be something like <filter object at 0x7fda689d8130>. When you iterate this object, you will get all the values that pass the condition defined in check().

def check(s):
if s in ['a', 'e', 'i', 'o', 'u']:
return False
return True

user_string = "alsjfdlaasdfknmnsfwirqpadsf"
filtered_list = filter(check, user_string)
print(filtered_list)

for value in filtered_list:
print(value, end = "")

'''
Output
<filter object at 0x7fda689d8130>
lsjfdlsdfknmnsfwrqpdsf
'''

Question 3: Does filter() work in Python2?

Answer: filter() does work in Python2. However, filter() in Python2 returns a list of values, whereas in Python3, it returns a filter object.

Looking for a Tech Interview Prep Coach?

Interview Kickstart offers the best technical interview prep courses that make you a better engineer and help you nail tech interviews.

As pioneers in the field of technical interview prep, we have trained thousands of software engineers to crack the toughest coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

For more information on what it takes to prepare for and succeed at FAANG tech interviews, sign up for our free webinar

<h2>Recommended Reading

Check out our learn page for articles on Python, Java, and more:

To hone your tech interview prep, go to our blog and interview questions pages:

------------

Article contributed by Problem Setters Official

Last updated on: 
April 1, 2024
Author

Vartika Rai

Product Manager at Interview Kickstart | Ex-Microsoft | IIIT Hyderabad | ML/Data Science Enthusiast. Working with industry experts to help working professionals successfully prepare and ace interviews at FAANG+ and top tech companies

Attend our Free Webinar on How to Nail Your Next Technical Interview

Register for our webinar

How to Nail your next Technical Interview

1
Enter details
2
Select webinar slot
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.

Filter() in Python

Worried About Failing Tech Interviews?

Attend our webinar on
"How to nail your next tech interview" and learn

Ryan-image
Hosted By
Ryan Valles
Founder, Interview Kickstart
blue tick
Our tried & tested strategy for cracking interviews
blue tick
How FAANG hiring process works
blue tick
The 4 areas you must prepare for
blue tick
How you can accelerate your learnings
Register for Webinar
entroll-image