[ACCEPTED]-Why does list.append evaluate to false in a boolean context?-list
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).
None evaluates to
False and in python a function 2 that does not return anything is assumed 1 to have returned
If you type:
>> print u.append(6) None
.append method returns
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'
It modifies the list in-place, and returns 1
None evaluates to false.
Actually, it returns
>>> print u.append(6) None >>> print not None True >>>
append modifies the list in-place and the 17 return value
In your case, you are creating 16 an array —  — on the fly, then discarding 15 it. The variable b ends up with the return 14 value of None.
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:
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.
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