Why Does List.append Evaluate To False In A Boolean Context?
Solution 1:
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).
Solution 2:
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 :)
Solution 3:
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'
Solution 4:
It modifies the list in-place, and returns None
. None
evaluates to false.
Solution 5:
Actually, it returns None
>>>print u.append(6)
None
>>>printnotNone
True
>>>
Post a Comment for "Why Does List.append Evaluate To False In A Boolean Context?"