# How to filter elements of a list in Python

## Problem –

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

``In : 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 : pos = [n for n in nums if n > 0]

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

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

In : neg
Out: [-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 : pos = [n if n> 0 else 0 for n in nums]

In : pos
Out: [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 : pos = (n for n in nums if n > 0)

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

In : 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 : nums = [1, 7, -4, '?', 'N/A', 8, -9]

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

In : pos = list(filter(is_pos, nums))

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

Rating: 1 out of 5.