×

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 program to check whether a given number is prime or not

Python program to check whether a given number is prime or not A positive integer greater than 1 is called a prime number if it is divisible by one and number...

1 minute read.

Python Generator

Python Generator: A Function is said to be a Python Generator that produces or generates a sequence of results. A Python Generator maintains its native state to work so that...

6 minutes read.

Python try catch exception

The try-except proclamation can deal with exceptions. Exceptions might happen when you run a program. Exceptions are blunders that occur during the execution of the program. Python won't educate you regarding...

3 minutes read.

Confusion Matrix Visualization Python

The confusion matrix is a two-dimensional array that compares the anticipated and actual category labels. These are the True Positive, True Negative, False Positive, and False Negative classification categories for...

4 minutes read.

Python Loop through a Dictionary

Introduction in this tutorial, we will discuss in python How to Loop Through a Dictionary. In contrast to other Data Types, which can only retain a single value as an element, a Dictionary...

4 minutes read.

Palindrome In Python

What is Palindrome? A Palindrome can be defined as the number or a string that resides unchanged when it is reversed. Example: 14341 Output: Yes, this is a Palindrome number Example: RACECAR Output: Yes, this...

2 minutes read.

Python dir() function

Python dir() function The dir() function in Python returns all properties and methods of the specified object, without the values. Syntax dir([object]) Parameter object: This parameter represents the object one wants to see the valid attributes. Return This function...

2 minutes read.

XXhash Python Examples

XXhash Python: xxHash is an extremely rapid hash calculation that operates inside the confines of RAM. Code is incredibly convenient, and hashes (almost nothing/large endian) are same at all levels. Execution of...

4 minutes read.

Allocate a minimum number of pages in python

You have given a sorted array of size n which represents the number of pages in n different books and an integer value which denotes the number of students. We...

4 minutes read.

Python Kwargs Example

In this article, we'll talk about Python's kwargs notion. In Python, kwargs has two stars and passes a variable number of keyworded argument lists to the function, whereas args has...

5 minutes read.

How to Convert Int to String in Python?

Every value we use or store in a variable in Python will have a specific data type. It describes the value's nature; based on that, Python will automatically assign a...

4 minutes read.

CSV Write in Python

What is meant by CSV? CSV stands for Comma Separated Values. The name itself defines its purpose. CSV arranges the data in the form of tables and stores the organized data in...

3 minutes read.

Pillow Python introduction and setup

Introduction Advanced image processing implies handling the picture carefully with the assistance of a PC. Utilizing picture handling we can perform activities like upgrading the picture, obscuring the picture, separating text...

4 minutes read.

Python Set clear() Method

Python Set clear() Method The set.clear() method removes all the elements from the set. Syntax set.clear() Parameter NA Return None Example 1 # Python program explaining # the set.clear() method # initializing the set fruits = {"watermelon", "banana", "apple"} # printing the set...

2 minutes read.

Exit program in python

Exit program in python The quit(), exit(), and sys.exit() functions have almost the same functionality as they raise the SystemExit exception by which the Python interpreter exit and no stack traceback...

2 minutes read.

Spyder (32-bit) - Free download

Spyder is a free and open-source scientific environment created by and for Python engineers, scientists, and data analysts. It is a robust scientific environment created in Python by and for...

3 minutes read.

Python Lists vs Tuples

The difference between lists and tuples is one of the most frequently asked questions in an interview related to python language. Lists and Tuples are two of Python’s built-in data...

4 minutes read.

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.

Difference between Perl and Python

Control and presently utilized for a great many undertakings, including framework organization, web improvement, network programming, and GUI improvement, and the sky is the limit from there. About Perl? Perl is a...

4 minutes read.

Python String strip() method

Python String strip() method The string. strip() method in Python removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to...

1 minute read.