×

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

Length of Tuple in Python

What is Tuple? Python is a data structure in a python programming language; it is the collection of the objects in a sequence. The tuples are immutable; that is, we cannot...

3 minutes read.

Subprocess in Python

In this tutorial, we will understand what is a subprocess in python and will understand how to use it. Subprocess A subprocess is a very prevailing portion of the python library. It...

3 minutes read.

Python Rest API

In this tutorial, we will understand the meaning of API and REST API. We will understand the working of REST API. We will then realize the boundaries of architecture defined...

4 minutes read.

Python EOL (End Of Line)

Introduction An EOL (End Of Line) is defined as a syntax error that indicates that the Python interpreter reached at the end of the line when it tried to scan a...

3 minutes read.

Python Tuple count() Method

Python Tuple count() Method The tuple.count() method in Python returns the number of times a specified value appears in the tuple. Syntax tuple.count(value) Parameter value- This parameter represents the element to search in the tuple Return This...

1 minute read.

Crash Course on Python by Google

There is a new, free Python programming course offered by Google on Coursera. No programming experience is necessary. There are numerous Python courses available, but when you learn that Google is...

5 minutes read.

Face Recognition in Python

In this tutorial, we will understand what is face recognition and how it is achieved in python. Face recognition is of great utility in real-world scenarios. It is an extended step...

3 minutes read.

Python Set isdisjoint() method

Python Set isdisjoint() method The set.isdisjoint() method in Python returns a boolean value True if two sets are disjoint sets ( i.e. none of the elements are present in both sets), otherwise it returns...

1 minute read.

Python program to check if two strings are anagram or not

Python program to check if two strings are anagram or not Problem: This is a python program that takes two strings and checks if given strings are anagram or not. Examples: Input: string1...

1 minute read.

Python any() Function

Python any() Function The any() function in Python returns a boolean value ‘True’ if any element of the iterable is true or if the iterable is empty, else it returns False. Syntax any(iterable) Parameter Iterable: An iterable object (list, tuple, dictionary) Return This...

1 minute read.

How to Make an App with Python

In this age of mobiles, rapid mobile application development has got a lot of traction. Moreover, app developers are high in demand because of the increase in digitization. Generally, Python is...

4 minutes read.

Python Program to Find the Greatest Among Three Numbers

Python Program to find the greatest among three numbers We have many approaches to get the largest of three numbers, and here we will discuss a few of them. This python...

2 minutes read.

Type casting in Python

Introduction Type Casting is defined as the method of converting the variables/values data type into a certain data type for matching the operation needed to be performed by the users. This...

4 minutes read.

Python min() function

Python min() function returns you the minimum value element in an iterable. We can also use this function to determine the smallest value among various arguments passed to this function. We...

4 minutes read.

How to Write a Configuration file in Python

This article will discuss How to write a configuration file in python, why we need config files in Python, the format of the configuration file, file extensions, and how to...

11 minutes read.

Python Support

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.

Python Word Tokenizer

Python Overview 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. Python is an interpreted language...

4 minutes read.

Python String endswith() method

Python String endswith() method The string.endswith() method in Python returns a Boolean value True if the string ends with the specified suffix, otherwise it returns False. Syntax endswith(suffix[, start[, end]]) Parameter suffix – This parameter represents a string or tuple...

2 minutes read.

Python hash() function

Python hash() function The hash() function in Python returns the hash value of the object (if it has one).  Syntax hash(object) Parameter obj : This parameter represents the object which we need to convert into hash. Return This...

1 minute read.

Applications of Python

Top 10 Applications of Python in 2020- 2021 Python language is famous for its general-purpose nature, which enables developers to use it in every field of development. Python can be found...

6 minutes read.