[Tutor] filter() builtin function

Cameron Simpson cs at cskk.id.au
Thu Sep 30 05:22:52 EDT 2021


On 30Sep2021 14:29, Manprit Singh <manpritsinghece at gmail.com> wrote:
>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*

A true object will do.

>*Like if I need only odd numbers from a list , what will be the correct
>lambda function to be placed inside the filter function ?*

A test that a number is odd:

    lambda n: test-if-n-is-odd

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

That would do. I would probably be inclined to go the whole way:

    lambda x: x%2 == 1

to make my meaning clear.

>*lambda x : x%2 == 1 ( Will return Boolean True for odd  numbers)*

I'd do that, but only for purposes of clarity.

>seq = [2, 3, 6, 9, 0, 7]
>list(filter(lambda x: x%2, seq))
>gives the answer
>= [3, 9, 7]

Seems correct.

>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're both correct. The second one more precisely specifies "oddness".

You seem heavily invested in "correct" and 'acceptable" ways to do 
things. For many of us, there are good ways and bad ways to do things, 
but things are only "incorrect" if they will give wrong answers i.e.  
they are buggy.

As usual my generic advice is:
- concise
- readable

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list