tags:

views:

279

answers:

5

Is there a reason being list.append evaluating to false? Or is it just the C convention of returning 0 when successful that comes into play?

>>> u=[]
>>> not u.append(6)
True
+12  A: 

None evaluates to False and in python a function that does not return anything is assumed to have returned None.

If you type:

>> print u.append(6)
None

Tadaaam :)

Matthieu M.
Mutators (like append, extend, sort, etc.) which update a list do not return a value.
S.Lott
+4  A: 

It modifies the list in-place, and returns None. None evaluates to false.

Matt Anderson
+2  A: 

because .append method returns None, therefore not None evaluates to True. Python on error usually raises an error:

>>> a = ()
>>> a.append(5)
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    a.append(5)
AttributeError: 'tuple' object has no attribute 'append'
SilentGhost
Actually `None` evaluates to `False`, the OP is tricky and uses `not`.
Matthieu M.
that was fixed before your comment :)
SilentGhost
+1  A: 

Actually, it returns None


>>> print u.append(6)
None
>>> print not None
True
>>> 

adam
+10  A: 

Most Python methods that mutate a container in-place return None -- an application of the principle of Command-query separation. (Python's always reasonably pragmatic about things, so a few mutators do return a usable value when getting it otherwise would be expensive or a mess -- the pop method is a good example of this pragmatism -- but those are definitely the exception, not the rule, and there's no reason to make append an exception).

Alex Martelli
I bumped into the issue while writing (y.append(5) and (yield y)) where I didn't expect a successful list addition to (indirectly) evaluate to false.
diciu