Why doesn't [].extend(list1) create an identical list to list1?

Question:

The analogue for strings holds true:

string1 = 'abc'
''.join(string1) == string1 # True

So why doesn’t this hold true:

list1 = ['a', 'b', 'c']
[].extend(list1) == list1 # AttributeError: 'NoneType' object has no attribute 'extend'

type([]) returns list. Why would it get perceived as a NoneType instead of a list which would have the extend method?

This is an academic question. I wouldn’t do this is regular code, I just want to understand.

Asked By: Ben Mordecai

||

Answers:

Because list.extend() modifies the list in place and does not return the list itself. What you’d need to do to get what you expect is:

lst = ['a', 'b', 'c']
cplst = []
cplst.extend(lst)
cplst == lst

The functions you reference are not really analogous. join() returns a new string created by concatenating the members of an iterator together with the string being joined on. An analogous list operation would look more like:

def JoiningList(list):

    def join(self, iterable):
        new_list = iterable[0]
        for item in iterable[1:]:
            new_list.extend(self)
            new_list.append(item)
        return new_list
Answered By: Silas Ray

Your’re trying to compare the return value of the extension to the list. extend is an in-place operation, meaning that it doesn’t return anything.

join, on the other hand, actually returns the result of the operation, so it is possible to compare the two strings.

Answered By: Volatility
>>> first = [1,2,3]
>>> second = []
>>> second.extend(first)
>>> first == second
True
Answered By: Brenden Brown
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.