one to many (passing variables)

Chris Angelico rosuav at
Sat Jul 26 04:53:09 CEST 2014

On Sat, Jul 26, 2014 at 11:47 AM, C.D. Reimer <chris at> wrote:
> Isn't a zero-length array, empty collection and null all the same thing?

Definitely not. In C++ and Java, which he's primarily looking at,
there's a definite difference in usage, and potentially in memory

> Or does the "Demand Exceptional Processing" comes from testing to see if the
> object is empty versus being null?
> And does this apply to Python?

In Python, if you have something that might return a list of
somethings, but in certain circumstances won't have any to return,
don't have it return None in that case; just return an empty list.

def func(args):
    if condition: return None
    return [1,2,3]

x = func(142857)
if x:
    for i in x:

With this:

def func(args):
    if condition: return []
    return [1,2,3]

x = func(142857)
for i in x:

The second one will always return a list, ergo you can always iterate
over it. You can still use "if x" to see if you got the empty one.

The point he's making is distinctly stronger in Python than in C++ or
Java, to the extent that it's a complete non-issue. In lower-level
languages, returning a null pointer is cheaper than constructing a
zero-length array, and testing an array for contents is both slower
and more verbose than testing for null-ness; but in Python, the cost
difference between "return None" and "return []" is negligible (there
is a difference, of course, but honestly - if you're worried about
that, Python is the wrong language for you), and the difference
between "if x" and "if x" is... uhh, nonexistent. :) His point is that
it's better to make things simple and clear and understandable than to
save a little bit of memory by returning null rather than an empty
array; and I don't think any Python programmers will disagree.

(There are, of course, times when you need to distinguish between a
non-result and a result with no items in it, which would be done by
returning None and returning [], respectively. That's different. Then
it's part of your API, as a separate state.)


More information about the Python-list mailing list