Concate two lists in python using extend

Question:

I have two lists given below

l1=[1,2,3,4]
l2=[5,6,7,8]

If i perform l1.extend(l2) and print(l1), output is [1,2,3,4,5,6,7,8] as expected but if i assign it to a variable like b=l1.extend(l2) and print(b) the output is None.

Can anyone explain this why it is so ?

Asked By: Anil

||

Answers:

extend() works in place and returns None so you get the output of l1.extend(l2) returned as None.

Answered By: Krishna Chaurasia

The reason is that l1.extend updates the object itself (l1) and doesn’t return anything.

From Python docs:

list.extend(iterable)
Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.
Answered By: Shahar Glazner
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.