Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does [].append() not work in python?

Tags:

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?

like image 984
Kshitiz Sharma Avatar asked Jan 10 '13 19:01

Kshitiz Sharma


People also ask

Is list () and [] the same in Python?

In practical terms there's no difference. I'd expect [] to be faster, because it does not involve a global lookup followed by a function call. Other than that, it's the same.

Is [] a list in Python?

In Python, a list is created by placing elements inside square brackets [] , separated by commas. A list can have any number of items and they may be of different types (integer, float, string, etc.). A list can also have another list as an item.

Why is my append function returning None Python?

append() method returns None because it mutates the original list. Most methods that mutate an object in place return None in Python.

How does array append work in Python?

Append an Array in Python Using the append() functionPython append() function enables us to add an element or an array to the end of another array. That is, the specified element gets appended to the end of the input array.


2 Answers

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"

class FluentList(list):
    def append(self, value):
        super(FluentList,self).append(value)
        return self

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

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

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

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

    def sort(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.

like image 111
Thorsten Kranz Avatar answered Oct 24 '22 07:10

Thorsten Kranz


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.

like image 33
adarsh Avatar answered Oct 24 '22 06:10

adarsh