简体   繁体   中英

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.

n.netype' 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM