Explain the difference between the "append" and "extend" methods in Python lists.
Explain the difference between the 'append' and 'extend' methods in Python lists.
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
05-Jul-2023The
append()
andextend()
methods are both used to add elements to a list in Python. However, they have different behaviors.The
append()
method adds a single element to the end of a list. The length of the list itself will increase by one. For example, the following code will add the element4
to the end of the listlist1
:Python
The output of the code is:
Code snippet
The
extend()
method iterates over its argument adding each element to the list, extending the list. The length of the list will increase by however many elements were in the iterable argument. For example, the following code will add the elements5
and6
to the end of the listlist1
:Python
The output of the code is:
Code snippet
Here is a table summarizing the differences between
append()
andextend()
:append()
extend()
Here are some examples of how
append()
andextend()
can be used:Python