How to Filter Lists in Python
In this article, we show how to filter lists in Python.
So you may have a list of elements in Python code in which you want to filter out certain elements while keeping others.
Say that we have a list of numbers composed of negative and positive numbers but we want to filter out all negative numbers, we can do this in Python. We can also form a list in which we filter out all positive numbers and have a list of only negative numbers.
The easiest way to filter a list in Python is probably through using a list comprehension.
A list comprehension allows you to easily apply whatever filter is needed and has the added benefit to transform the data at the same time.
Below we use list comprehensions to first filter out all negative numbers from
a list and then we do a second example to filter out all positive numbers from a list.
So we have our list named list1, which contains both positive and negative numbers.
We then have a list comprehension that only includes numbers that are positive (above 0).
You can then see that all negative numbers are removed and only positive numbers are in the list.
We then do the same with negative numbers.
We create a list comprehension that only includes numbers that are negative (below 0).
You can see that all positive numbers are removed and only negative numbers are in the list.
So using list comprehensions in Python, we can apply filters that we specify such as with if statements. Only items in the list that satisfy the condition will be included in the list.
List comprehensions like this in Python are lists. List comprehensions are just
setting up the lists in a way that you can add in requirements to filter the list to be able to
exclude certain items. However, the output of a list comprehension is a list.
And this is how we can filter lists in Python.
Related Resources
How to Create a Zip File in Python
How to Extract All Files and Folders from a Zip File in Python
How to Read the Contents of a Zip File in Python