[ACCEPTED]-Why does list.append evaluate to false in a boolean context?-list

Accepted answer
Score: 44

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

Score: 19

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

If you type:

>> print u.append(6)
None

Tadaaam :)

Score: 7

because .append method returns None, therefore not None evaluates 1 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'
Score: 5

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

Score: 3

Actually, it returns None


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

0

Score: 1

Method append modifies the list in-place and the 17 return value None

In your case, you are creating 16 an array — [6] — on the fly, then discarding 15 it. The variable b ends up with the return 14 value of None.

Why?
This comply with the 13 principle of Command–query separation devised by Bertrand Meyer.
It 12 states that every method should either be 11 a command that performs an action, or a 10 query that returns data to the caller, but 9 not both. In your example:

u.append(6)

append modified the 8 state of [], so it’s not a best practice 7 to return a value compliance with the principle.

In 6 theoretical terms, this establishes a measure 5 of sanity, whereby one can reason about 4 a program's state without simultaneously 3 modifying that state.

CQS is well-suited 2 to the object-oriented methodology such 1 as python.

Score: 0

The list.append function returns None. It just adds the 3 value to the list you are calling the method 2 from.

Here is something that'll make things 1 clearer:

>>> u = []
>>> not u
False
>>> print(u.append(6)) # u.append(6) == None
None    
>>> not u.append(6) # not None == True
True

More Related questions