Explain the difference between "append()" and "extend()" methods in Python lists.
Explain the difference between "append()" and "extend()" methods in Python lists.
207
26-Jun-2023
Aryan Kumar
27-Jun-2023Sure. The
append()andextend()methods are both used to add elements to a list in Python. However, they work in slightly different ways.The
append()method adds a single element to the end of a list. For example, the following code adds the number 5 to the end of the listlist1:Python
This will print the list
[1, 2, 3, 5].The
extend()method adds the elements of an iterable to the end of a list. For example, the following code adds the numbers 6, 7, and 8 to the end of the listlist1:Python
This will print the list
[1, 2, 3, 6, 7, 8].The main difference between the
append()andextend()methods is that theappend()method only adds a single element to the end of a list, while theextend()method can add multiple elements to the end of a list.Here is a table that summarizes the differences between the
append()andextend()methods:append()extend()