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 ?
Answers:
extend()
works in place and returns None
so you get the output of l1.extend(l2)
returned as None
.
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.
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 ?
extend()
works in place and returns None
so you get the output of l1.extend(l2)
returned as None
.
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.