Skip to content Skip to sidebar Skip to footer

Why Does [].append() Not Work In Python?

Why does this work - a = [] a.append(4) print a But this does not - print [].append(4) The output in second case is None. Can you explain the output?

Solution 1:

The append method has no return value. It changes the list in place, and since you do not assign the [] to any variable, it's simply "lost in space"

classFluentList(list):
    defappend(self, value):
        super(FluentList,self).append(value)
        return self

    defextend(self, iterable):
        super(FluentList,self).extend(iterable)
        return self

    defremove(self, value):
        super(FluentList,self).remove(value)
        return self

    definsert(self, index, value):
        super(FluentList,self).insert(index, value)
        return self 

    defreverse(self):
        super(FluentList,self).reverse()
        return self

    defsort(self, cmp=None, key=None, reverse=False):
        super(FluentList,self).sort(cmp, key, reverse)
        return self

li = FluentList()
li.extend([1,4,6]).remove(4).append(7).insert(1,10).reverse().sort(key=lambda x:x%2)
print li

I didn't overload all methods in question, but the concept should be clear.

Solution 2:

The method append returns no value, or in other words there will only be None

a is mutable and the value of it is changed, there is nothing to be returned there.

Solution 3:

append returns None.

from your example:

>>> print a.append(4)
None

Post a Comment for "Why Does [].append() Not Work In Python?"