ID : 250
viewed : 117
Tags : PythonPython List
99
This article introduces the difference between list append
and extend
methods in Python.
append
Methodappend
adds the object to the end of the list. The object could be any data type in Python, like list, or class object.
>>> A = [1, 2] >>> A.append(3) >>> A [1, 2, 3] >>> A.append([4, 5]) >>> A [1, 2, 3, [4, 5]]
The length of the list will increase by one after the append
is done.
extend
Methodextend
extends the list by appending elements from the iterable argument. It iterates over the argument and then adds each element to the list. The given argument must be iterable type, like list, otherwise, it will raise TypeError
.
>>> A = [1, 2] >>> A.extend(3) Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> A.extend(3) TypeError: 'int' object is not iterable
If you want to add 3
to the end of the list, you should firstly put the 3
in a new list.
>>> A = [1, 2] >>> A.extend([3]) >>> A [1, 2, 3]
extend
method iterates the elements in the iterable object and then adds them one to one to the end of the list.
>>> A = [1, 2] >>> A.extend([3, 4]) >>> A [1, 2, 3, 4]
extend
String TypeBe aware that when the given object is a string
type, it will append each character in the string to the list.
>>> A = ["a", "b"] >>> A.extend("cde") >>> A ['a', 'b', 'c', 'd', 'e']
append
and extend
in Python Listappend
adds the given object to the end of the list, therefore the length of the list increases only by 1.
On the other hand, extend
adds all the elements in the given object to the end of the list, therefore the length of the list increases by the length of the given object.