+ 3
append vs extend
What is the difference between .append and .extend? Which one used for what??
4 ответов
+ 5
Just like brains said, Append includes x element into existing list ex.
a = 1
list1 = [1, 2, 3]
list1.append(a) = [1,2,3,1]
and with extend
list1 = [1,2,3]
list2 = [1,1,1]
list1.extend(list2) = [1,2,3,1,1,1]
but if you'd use append in the previous case instead of extend.
list1 = [1,2,3]
list2 = [1,1,1]
list1.append(list2) = [1,2,3,[1,1,1]]
+ 3
append includes an element in a list,extend concatenates or joins lists
+ 1
the method extend works as a list concatenation.
following the examples of of Markus,
list1=[1,2,3]
list2=[4,5,6]
list1.extend(list2)=[1,2,3,4,5,6]
works same as + operation,
list1=[1,2,3]
list2=[4,5,6]
print(list1+list2)