[Tutor] filter() builtin function

Alan Gauld alan.gauld at yahoo.co.uk
Thu Sep 30 05:54:26 EDT 2021


On 30/09/2021 09:59, Manprit Singh wrote:
> Dear sir,
> 
> For the filter function in Python documentation ,  a line is written as
> below:
> 
> Construct an iterator from those elements of *iterable* for which *function*
> returns true.
> 
> *What does that true means - Boolen  value True or true object 

In lower case it means something that Python considers true.
True, Non-empty, non-zero etc.

> *lambda x: x%2  (That will return 1  for odd numbers which is a true
> object)*
> 
> *or *
> 
> *lambda x : x%2 == 1 ( Will return Boolean True for odd  numbers)*

Why not just try it and see? The interpreter is the definitive answer.

> *seq = [2, 3, 6, 9, 0, 7]list(filter(lambda x: x%2, seq)) gives the answer
> = *[3, 9, 7]
> 
> seq = [2, 3, 6, 9, 0, 7]
> list(filter(lambda x: x%2 == 1, seq))  also gives the same answer = [3, 9,
> 7]
> 
> Which one is the correct  way to do the task solved  just above  in 2 ways ?

They are both correct.

And in modern python the normal way to do this would be to use neither.
Instead use a list comprehension or generator expression:

[n for n in seq if n%2]

filter is rarely(never?) needed nowadays.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list