Python - Selecting Items in Iterables: filter

Introduction

filter function selects an iterable's items based on a test function.

filter function requires a list call to display all its results.

For example, the following filter call picks out items in a sequence that are greater than zero:

Demo

d=list(range(-5, 5))                                   # An iterable in 3.X 
print( d )
d=list(filter((lambda x: x > 0), range(-5, 5)))        # An iterable in 3.X 
print( d )

Result

Items in the sequence or iterable for which the function returns a true result are added to the result list.

It is roughly equivalent to a for loop as follows:

Demo

res = [] 
for x in range(-5, 5):    # The statement equivalent 
   if x > 0: 
       res.append(x) #  ww w .j av  a2  s .c o  m
print( res )

Result

filter can be emulated by list comprehension syntax.

Demo

d=[x for x in range(-5, 5) if x > 0]                   # Use () to generate items 
print( d )

Result