Press "Enter" to skip to content

Python Notes 11 : Filter & Zip built in functions

filter function

Syntax

filter(function,list)

filter function filters out all the elements of an iterable for which the function returns true. It must be noted here that function used with filter function must return a boolean value.

Example

lst =range(20)
filter(lambda x: x%2==0,lst)

Output

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Zip function

Zip function takes in two sequences as arguments and returns cartesian product of the two. It stops when the shortest input is exhausted.

Example 1:-
x = [1,2,3]
y = [4,5,6,7]

# Zip the lists together
zip(x,y)
Output
[(1, 4), (2, 5), (3, 6)]
Note - Tuples are returned here.

Example 2:- Zip with dictionaries
d1 = {'a':1,'b':2}
d2 = {'c':4,'d':5}

zip(d1,d2)
Output
[('a', 'c'), ('b', 'd')]
Note - Simply iterating through dictionaries will result in just the keys
zip(d2,d1.itervalues())
Output
[('c', 1), ('d', 2)]

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *