×

Python Filter List

To filter a list, we use filter () method function. The filter () will test every element true or not in the sequence.

Syntax:

Filter(function, sequence)

Parameters:

  • Function: Function that check and verifies if each number of a sequence true or not.
  • Sequence: sequence has to filter numbers from the list, sets or tuples of any iterator.
  • Returns: Returns already filtered numbers from an iterator.

Examples

  • Example program for filtering vowels and sequence:
deffun(variable):
    alpha =['u', 'o', 'i', 'e', 'a']
    if(variable inalpha):
        returnTrue
    else:
        returnFalse
sequence =['z', 'a', 'e', 'm', 'k', 'x', 'v', 'r']
  
// using filter function  
Print('filtered elements:')
form infiltered:
    print(m)

Output:

Filtered elements:
a
e
  • Example program for odd and even numbers:
sequence=[6,7,8,9,0,5]
  
// odd elements of the list
res =filter(lambdax: x %2!=0, seq)
print(list(res))
  
// even elements of the list
res =filter(lambdax: x %2==0, seq)
print(list(res))

Output:

[5, 7, 9]
[0, 6, 8]

Approaches

For filtering list, we have three approaches:

  1. A for loop approach
  2. A list comprehension
  3. filter () method function.

A For Loop Approach

  • A for loop will be repeated until its condition fails.
  • A for loop goes through every number of a list.
  • Based upon the condition numbers are added.

Example:

ages = [15,18,20,10,30]
young_ages = []
for age in ages:
    if age >= 18:
young_ages.append(age)
print(young_ages)

Output:

[18, 20, 30]

List Comprehension Approach

In short, list comprehension is a shorthand for looping through a list with one line of code. It follows this syntax:

[number for number in numbers if condition]

Example:

ages = [15, 18, 20, 10, 30]
young_ages = [age for age in ages if age >= 18]
print(young_ages)

Output:

[18, 20, 30]

Filter () Function

The filter () function returns a filter object with the filtered elements. You can convert this filter object into a list using the list() function.

Syntax:

Filter (function, numbers)

Example:

Filtering function that tests ages.

def age_test(age):
    return age >= 18
// passing age_test () function
ages = [15, 18, 20, 10, 30]
young_ages = filter(age_test, ages)
print(list(young_ages))

Output:

[18, 20, 30]

Related Topics

Python MySQL Update Operation

Python MySQL Update Operation: In this part of tutorial, we will learn that how can we update a table present in SQL database through our Python program. As like SQL,...

4 minutes read.

Python List

The list is one of the most versatile, mutable data-structures in Python. It can store heterogeneous data or different types of data. The list contains comma-separated values (item) within the square brackets. Creating...

4 minutes read.

Difference between Package and Module in Python

What are Python modules? A file with the “.py” suffix that includes Python or C executable code is known as a module. Multiple Python commands and expressions make compose a module....

3 minutes read.

Python set()

Python set() Class The set() class in Python returns a new set object, optionally with elements taken from iterable.  Syntax class set([iterable]) Parameter iterable : This parameter represents a sequence, collection or an iterator object Return This function returns a...

1 minute read.

How to Import Files in Python

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Permutations in Python

Recursion Basic idea: for numbers of length N. N-1 items are chosen at random between 0 and then generate permutations using the remaining N-1 elements in a recursive fashion. Once you've done...

4 minutes read.

Data Drop in Python

Introduction You'll understand how to delete a group of rows from a Pandas dataframe in this article.You can read this article on How to Drop Columns in Pandas to find out...

6 minutes read.

Python String lower() method

Python String lower() method The string.lower() method in Python returns a string where all characters are lower case. Syntax string.lower() Parameter NA Return This method returns a string where all characters are lower case. Example 1 # Python...

1 minute read.

Working with JSON in Python

Python is an Object-Oriented high-level language. Python is designed to be highly beginner-friendly. Python has an English-like syntax, which is very easy to read. In this article, we are going...

4 minutes read.

Python Typing Module

An Introduction to the Typing Module The typing module is introduced in Python version 3.5 and used to provide hinting method types in order to support static type checkers and linters...

10 minutes read.

Python vars() Function

Python vars() Function The vars() function in Python returns the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute. Syntax vars([object]) Parameter object: This parameter represents any object with a __dict__attribute Return This function returns...

1 minute read.

How to create a file in Python?

How to create a file in python? Files provide us a convenient way of storing our information. Once we have our data, the next task is to store it so that...

3 minutes read.

Python Dictionary update() method

Python Dictionary update() method The dictionary.update() method in Python inserts the specified items to the dictionary. Syntax dictionary.update(iterable) Parameter iterable- This parameter represents a dictionary or an iterable object with key value pairs, that will...

1 minute read.

Python MongoDB Tutorial

An Introduction to MongoDB MongoDB is a document-oriented database application. It is an Open-source and platform-independent program. MongoDB is similar to few NoSQL databases that store the data in the documents...

17 minutes read.

Python List sort() method

The list.sort () method in Python sorts the items of the list in place. Syntax list.sort(key=None, reverse=False) Parameter reverse: If a Boolean value ‘True’ is passed, the  sorting will be done in the descending order else for ‘False’...

2 minutes read.

How to make API calls in Python

Information is extremely critical these days since it drives applications and organizations. It is subsequently critical to figure out how to get this information to serve your application. In fundamental...

4 minutes read.

How to append a string in python

Adding or appending a string to another string is easy in Python. It is called concatenation and is a basic concept of strings in almost all programming languages. Ways to Append...

4 minutes read.

Python Tuple Methods

Python Tuple Methods Python has two built-in methods that are used for tuples. The following are the two methods: Method Description count() The tuple.count() method in Python returns the number of times a...

1 minute read.

Python String find() method

Python String find() method The string.find() method in Python finds the first occurrence of the specified value and returns the lowest index in the string if the substring sub is found else it...

2 minutes read.

Sentiment Analysis using NLTK

Introduction Data is being produced at an astounding rate and volume in the field of the internet and other digital services nowadays. Researchers, engineers, and data analysts often work with tabular...

7 minutes read.