Is there a way to get the following result in Python?

Cameron Simpson cs at cskk.id.au
Tue Jun 15 01:03:16 EDT 2021


On 11Jun2021 19:02, Jach Fong <jfong at ms4.hinet.net> wrote:
>>>> def foo():
>...     # do something
>...
>>>> a = []
>>>> for i in range(3):
>...     a.append(foo())
>...
>>>> a
>[]
>>>>

Chris has explained that what you've written will never do it. But if 
instead you wanted to filter out None results, getting an empty list 
from the filter, then the filter() builtin function will do you.

First, as Chris alluded to, all functions return values. Those with a 
"bare" return (no expression) or which just fall off the end of the 
function body actaully return None.

There's the obvious:

    a = []
    for i in range(3):
        item = foo()
        if item is not None:
            a.append(item)

Using a filter...  "help(filter)" says:

    >>> help(filter)
    Help on class filter in module builtins:

    class filter(object)
     |  filter(function or None, iterable) --> filter object
     |
     |  Return an iterator yielding those items of iterable for which function(item)
     |  is true. If function is None, return the items that are true.
     |
     |  Methods defined here:
     |
     |  __getattribute__(self, name, /)
     |      Return getattr(self, name).
     |
     |  __iter__(self, /)
     |      Implement iter(self).
     |
     |  __next__(self, /)
     |      Implement next(self).
     |
     |  __reduce__(...)
     |      Return state information for pickling.
     |
     |  ----------------------------------------------------------------------
     |  Static methods defined here:
     |
     |  __new__(*args, **kwargs) from builtins.type
     |      Create and return a new object.  See help(type) for accurate signature.

which is more that I expected. Usage:

    a = list(filter(lambda item: item is not None, items))

where items is the various returns from foo().

Or you could just write a list comprehension directly:

    a = [ item for item in items if items is not None ]

You want items to be your calls to foo(). Eg:

    a = [ item for item in (foo() for _ in range(3)) if items is not None ]

The (expression for name in iterable) is a generator expression. Like a 
list comprehension but it is a generator - it only runs as it is 
consumed. A list comprehension makes an actual list (stores all the 
results in the list).

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


More information about the Python-list mailing list