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

Chris Angelico rosuav at gmail.com
Mon Jun 14 15:41:07 EDT 2021


On Tue, Jun 15, 2021 at 5:23 AM Jach Feng <jfong at ms4.hinet.net> wrote:
>
> >>> def foo():
> ...     # do something
> ...
> >>> a = []
> >>> for i in range(3):
> ...     a.append(foo())
> ...
> >>> a
> []
> >>>
>

Barring shenanigans like messing with globals, no, there is no way for
a function to return a lack of value. Fundamentally, EVERY expression
in Python has to have a value, and that value must be a single object.
The only exception - pun intended - is if the function doesn't return
at all, eg if "# do something" is "raise Exception". But if that
happens, you won't have the output you're looking for either, unless
you wrap the append in a try/except.

So, no. There is no "return emptiness" concept. You can be 100%
confident that "a.append(foo())" will always append exactly one value,
if the following line of code is indeed executed.

ChrisA


More information about the Python-list mailing list