Search code examples
pythonlistconcatenationextend

Difference between extend() and + in lists - python


I want to know what is the exact difference between l1+l2 and l1.extend(l2) as it both concatenates the lists in python.

I have already went through the below post regarding the same question.

Concatenating two lists - difference between '+=' and extend()

I clearly understand that extend() involves a function call and hence can be a bit more expensive. And also l1+l2 option cannot be used for non-local variables.

But in my case, I had a recursive code which eventually returns concatenation of two lists. I used extend method l1.extend(l2). And i got the following errors.

nonetype' object is not iterable

object of type 'NoneType' has no len()

But note that the list is not None or of NoneType. I even tried printing the type(l1) and len(l1) and the type is list only.

But one thing is that, if i replace extend method with l1 + l2, entire code works fine and i didn't get any error.

May I know why is this so? Any ideas/suggestions


Solution

  • >>> print(l1.extend(l2))
    None
    

    l1.extend(l2) returns none while l1 has been updated. The mistake (but without code we can't tell for sure) is probably that you need to assign l1.extend(l2) to a (new) variable again.