[Tutor] filter() builtin function

Roel Schroeven roel at roelschroeven.net
Thu Sep 30 05:16:05 EDT 2021


Op 30/09/2021 om 10:59 schreef Manprit Singh:
> 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 - for
> example 1*
It's not stated explicitly but they probably mean 'true' as a shorthand 
for 'any value which evaluates to True in a boolean context'. That means 
True, numbers different from 0, non-empty collections and strings, and 
probably some other things I'm forgetting. Basically anything for which 
bool(thing) == True.
> *Like if I need only odd numbers from a list , what will be the correct
> lambda function to be placed inside the filter function ?*
>
>
> *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)*
Both are correct and will generate the same answer. My preference is the 
second, because it states the intention much cleaner: keep the elements 
which have 1 as remainder when divided by 2 (which is what odd numbers 
are). Always remember that you write code as much for other programmers 
(including future yourself) as for the computer (even more for 
programmers than for the computer, one could argue), therefore barring 
significant performance issues it's always best to write code that best 
states your intention.

-- 
"Il semble que la perfection soit atteinte non quand il n'y a plus rien à
ajouter, mais quand il n'y a plus rien à retrancher."
"Perfectie is niet bereikt als er niets meer toe te voegen is, maar als er
niets meer weg te nemen is."
         -- Antoine de Saint-Exupéry



More information about the Tutor mailing list