How to filter elements of a list in Python

Spread the love

Problem –

You have a list and you want to filter the element of this list based on some criteria.

In [1]: nums = [ 1, 7, -4, -2, 5, -10, 8, -9]

Here, we have some numbers and we want to get the positive or negative integers from this list.

Solution –

List Comprehensions –

The easiest way to filter a list is using list comprehension.

In [2]: pos = [n for n in nums if n > 0]

In [3]: pos
Out[3]: [1, 7, 5, 8]

In [4]: neg = [n for n in nums if n < 0]

In [5]: neg
Out[5]: [-4, -2, -10, -9]

Sometimes, you may want to replace the value that does not satisfy a condition with something else. You can also accomplish this using list comprehensions. Let’s replace negative values with zeros.

In [6]: pos = [n if n> 0 else 0 for n in nums]

In [7]: pos
Out[7]: [1, 7, 0, 0, 5, 0, 8, 0]

Generators –

List comprehension is OK if the list is not big enough and if the list is massive that you may not want to use list comprehension as it will create a massive list. In this situation you can use generators in python.

In [8]: pos = (n for n in nums if n > 0)

In [9]: pos
Out[9]: <generator object <genexpr> at 0x0000022980AC3C48>

In [10]: for i in pos:
    ...:     print(i)
    ...:     
1
7
5
8

Filter –

Another way to filter data from lists is using filter in python. To filter data, you have to first create a function that apply the filtering logic then you have to apply filter.

In [12]: nums = [1, 7, -4, '?', 'N/A', 8, -9]

In [13]: def is_pos(val):
    ...:     try:
    ...:         if val > 0:
    ...:             return True
    ...:     except TypeError:
    ...:         return False
    ...:         

In [14]: pos = list(filter(is_pos, nums))

In [15]: pos
Out[15]: [1, 7, 8]

Rating: 1 out of 5.

Leave a Reply