-3

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

  • You clearly know the difference, so go find out why your code is returning a None type at the spot. – dfundako Jun 11 '20 at 19:40
  • Please add an [example](https://stackoverflow.com/help/minimal-reproducible-example) illustrating the same. – Raghul Raj Jun 11 '20 at 19:40
  • `l1+l2` creates a *new list*, independent of either input list, and returns that. `l1.extend(l2)` modifies `l1`, and returns nothing. These aren't even close to being interchangeable pieces of code. – jasonharper Jun 11 '20 at 19:56
  • Thanks jasonharper. Understood that, l1.extend(l2) just modifies the the list but returns None and not the modified l1 list.. Thanks! – Abhishek L Jun 14 '20 at 10:41

1 Answers1

0
>>> 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.

Ronald
  • 2,930
  • 2
  • 7
  • 18